使用空格将JSON属性解析为对象

时间:2015-07-22 15:24:51

标签: json json.net

我正在使用返回JSON的第三方系统。

我正在尝试解决如何反序列化以下json;

{"getResponse": {
    "Results": {
        "Result 1": {"Row": [{Name:Somename}]
     }
}

我正在使用Newtonsoft JSON库。任何人都知道如何将其解析为.Net对象?

2 个答案:

答案 0 :(得分:4)

要使用JsonConvert.DeserializeObject<T>将JSON解析为对象,您可以使用以下方法创建类结构:

public class RootObject
{
    public GetResponse getResponse { get; set; }
}

public class GetResponse
{
    public Results Results { get; set; }
}

public class Results
{
    [JsonProperty("Result 1")]
    public Result1 Result1 { get; set; }
}

public class Result1
{
    [JsonProperty("Row")]
    public List<Row> Rows { get; set; }
}

public class Row
{
    public string Name { get; set; }
}

然后像这样反序列化:

string json = @"
{
    ""getResponse"": {
        ""Results"": {
            ""Result 1"": {
                ""Row"": [
                    {
                        ""Name"": ""Somename""
                    }
                ]
            }
        }
    }
}";

RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Row row in root.getResponse.Results.Result1.Rows)
{
    Console.WriteLine(row.Name);
}

答案 1 :(得分:1)

我希望有更好的方法可以做到这一点,所以我希望有人能提供更好的答案。

鉴于以下(更正的)JSON;

{"getResponse": {
    "Results": {
        "Result 1": {"Row": [{"Name":"Somename"}]
     }
  }
}

我想反序列化Row数组中的元素,不知道如何使用自定义转换器执行此操作。

所以我的解决方案,直到我有时间找到更好的方法是这个;

JObject result = JObject.Parse(response);
var t = result["getResponse"]["Results"]["Result 1"]["Row"];
var els =                 
        JsonConvert.DeserializeObject<List<MyResponse>>(t.ToString());
相关问题