无法使用多个JObjects解析JSON

时间:2018-11-13 03:41:38

标签: c# .net json json.net

我有以下格式的字符串。我想将项目内的每个JSON分配给单独的JObject。当我尝试解析它并进行相应分配时,我无法实现它。我该如何解析?

 {
      "projects": [
        {
          "sno": "1",
          "project_name": "Abs",
          "project_Status": "Live"
        },
        {
          "sno": "2",
          "project_name": "Cgi",
          "project_Status": "Live"
        }
      ]
    }

我尝试了以下代码;

using (StreamReader streamReader = new StreamReader(Path.Combine(Path.GetTempPath(), "sample.json")))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
    var serializer = new JsonSerializer();
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            JObject jsonPayload = JObject.Load(reader);
            jsonProfile = jsonPayload.ToString();
            JObject json = JObject.Parse(jsonProfile);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用DeserializeAnonymousType作为解析json的更简单解决方案。

var definition = new
{
    projects = new[]{
            new {
              sno="1",
              project_name= "Abs",
              project_Status= "Live"
            }
    }
};

string json1 = @" {
                  'projects': [
                    {
                                'sno': '1',
                      'project_name': 'Abs',
                      'project_Status': 'Live'
                    },
                    {
                            'sno': '2',
                      'project_name': 'Cgi',
                      'project_Status': 'Live'
                    }
                  ]
                }";
var projects = JsonConvert.DeserializeAnonymousType(json1, definition);

但是如果您确实想使用strong type,则最好使用JsonProperty

public class Project
{
    [JsonProperty("sno")]
    public string Sno { get; set; }

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

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

public class JsonModel
{
    [JsonProperty("Projects")]
    public List<Project> projects { get; set; }
}

JsonConvert.DeserializeObject<JsonModel>(json_Data);