我如何阅读json的每个字段

时间:2016-12-22 08:14:44

标签: c# json json.net

我发布到API并获得回复

HttpWebResponse response = (HttpWebResponse)request.GetResponse();          
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var jsonResponse = JsonConvert.SerializeObject(responseString , Formatting.Indented);

这是 jsonResponse 的值:

"{\"Id\":333,
  \"Name\":\"TestProduct\",
  \"ApplicationId\":\"9edcc30d-7852-4c95-a6b2-1bf370655965\",
  \"Features\":[{
         \"Id\":301,
         \"Name\":\"Sodalis Mobile Client2.0\",
         \"Code\":\"Beeware.Sodalis.Mobile\",
         \"ProductId\":0,
         \"Selected\":null}]
}"

我怎样才能阅读每篇文章? 例如名称 ApplicationId 功能名称功能代码

我将不胜感激。

3 个答案:

答案 0 :(得分:2)

您必须创建一个类

public class Feature
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("Code")]
    public string Code { get; set; }

    [JsonProperty("ProductId")]
    public int ProductId { get; set; }

    [JsonProperty("Selected")]
    public object Selected { get; set; }
}

public class YourApp
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("ApplicationId")]
    public string ApplicationId { get; set; }

    [JsonProperty("Features")]
    public IList<Feature> Features { get; set; }
}

然后将其反序列化

YourApp p = JsonConvert.DeserializeObject<YourApp>(json);
Console.WriteLine(p.Name + p.ApplicationId);

您可以使用foreach阅读所有功能,因为现在您的对象中存在所有功能

foreach(Feature AllFeatures in p.Features)
{
    Console.WriteLine(AllFeatures.Name + AllFeatures.Code);
}

答案 1 :(得分:1)

首先,创建将保存您的回复的类:

public class MyResponse {
    public int Id {get; set;}
    public string Name {get; set;}
    public string ApplicationID {get; set;}
    public IList<MyFeature> Features {get; set;}
}

public class MyFeature {
    public int Id {get; set;}
    public string Name {get; set;}
    public int ProductId {get; set;}
    public string Selected {get; set;}

} 

然后您可以使用JsonConvert

MyResponse response = JsonConvert.DeserializeObject<MyResponse>(responseString);
string name = response.Name;

答案 2 :(得分:1)

试试这个课程

public class MyResponse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ApplicationID { get; set; }
    public List<MyFeature> Features { get; set; }
}

public class MyFeature
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string Code { get; set; }
    public int ProductId { get; set; }

    public bool? Selected { get; set; }

}

然后你可以通过这个

阅读json
string _Json = @"{'Id':333,'Name':'TestProduct','ApplicationId':'9edcc30d-7852-4c95-a6b2-1bf370655965','Features':[{'Id':301,'Name':'Sodalis Mobile Client2.0','Code':'Beeware.Sodalis.Mobile','ProductId':0,'Selected':null}]}";
MyResponse M = JsonConvert.DeserializeObject<MyResponse>(_Json);