简体   繁体   English

如何从C#中的特殊类型json字符串中检索数据?

[英]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. 我尝试使用JObject从上述代码中检索数据。 But it return an exception error. 但它返回异常错误。

在此处输入图片说明

How can I retrieve data from this json string? 如何从此json字符串检索数据? 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. 现在,您可以将obj作为普通的c#对象进行访问。

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.. 使用Newtonsoft json您也可以执行以下方法。我看到您在topScoringIntent附近有一个嵌套的Json,在实体附近有一个数组对象,所以我建议您使用JObject访问所有JSon数据,然后使用JArray访问数组元素并添加将它们添加到模型中并返回值。请尝试一下。

    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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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