简体   繁体   中英

How to retrieve data from special type json string in c#?

{
query: "find a flight to go to matara to galle",
topScoringIntent: {
intent: "Start Activity",
score: 0.999594033
},
entities: [
{
entity: "sri lanka",
type: "startAirport",
startIndex: 23,
endIndex: 28,
score: 0.8759165
},
{
entity: "india",
type: "endAirport",
startIndex: 33,
endIndex: 37,
score: 0.8645479
}
]
}

I try to retrieve data from above code using JObject. But it return an exception error.

在此处输入图片说明

How can I retrieve data from this json string? Please Help. thanks.

Add below model class inside your project

public class TopScoringIntent
{
    public string intent { get; set; }
    public double score { get; set; }
}

public class Entity
{
    public string entity { get; set; }
    public string type { get; set; }
    public int startIndex { get; set; }
    public int endIndex { get; set; }
    public double score { get; set; }
}

public class RootObject
{
    public string query { get; set; }
    public TopScoringIntent topScoringIntent { get; set; }
    public List<Entity> entities { get; set; }
}

Now

JavaScriptSerializer jss = new JavaScriptSerializer();
RootObject obj= jss.Deserialize<RootObject>(jsonText);

Now you can access obj as a normal c# object.

Using Newtonsoft json You can do the following method too.As I see you have a nested Json near topScoringIntent and array object near entities so i suggest you to use JObject to access all the JSon data and then use JArray to access the array elements and add them to your model and return the values.Try it one..

    JObject data = JObject.Parse(YourJsonData);
    JObject topScoringIntentData = JObject.Parse(data["topScoringIntent"]);
    JArray entitiesData = JArray.Parse(data["entities"].ToString());
    foreach(var item in entitiesData)
    {
          //access all the data in the entities
    };
    //if you want all the other datas access the Jobject and stor them in your appropriate datamodel 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM