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

时间:2016-06-20 08:01:11

标签: c# json

{
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
}
]
}

我尝试使用JObject从上面的代码中检索数据。但它返回异常错误。

enter image description here

如何从此json字符串中检索数据?请帮忙。谢谢。

2 个答案:

答案 0 :(得分:2)

在项目中添加以下模型类

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; }
}

现在

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

现在您可以将 obj 作为普通的c#对象访问。

答案 1 :(得分:0)

使用Newtonsoft json你也可以执行以下方法。我看到你有一个嵌套的Json靠近topScoringIntent和数组对象靠近实体所以​​我建议你使用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