从JSON数组中提取对象以列出

时间:2018-04-10 11:52:09

标签: c# json json.net

我正在使用C#代码,我得到的JSON服务结果如下:

[
{"value":"{\"code\":\"MO\",\"description\":\"Monday\",\"isSet\":false}","nr":1}
,{"value":"{\"code\":\"TU\",\"description\":\"Tuesday\",\"isSet\":true}","nr":2}
]

我想使用此数组中的反序列化值对象列表。但我的印象是我的代码有点麻烦。

JArray j = JArray.Parse(task.Result); 
List<Booking> b = j.Select(x => JObject.Parse(x["value"].ToString()).ToObject<Booking>()).ToList();

选择字符串并将它们解析为对象,然后真正按照这种方式进行转换?或者这可以更高效地完成吗?

1 个答案:

答案 0 :(得分:1)

使用以下类:

public class Value
{
    public string Code { get; set; }
    public string Description { get; set; }
    public bool IsSet { get; set; }
}

public class RootObject
{
    [JsonProperty("Booking")]
    public Value Value { get; set; }
    public int Nr { get; set; }
}

然后反序列化您的JSON字符串,如下所示:

var test = JsonConvert.DeserializeObject<List<RootObject>>(json);

JSON字符串需要取消转义:

[
{"value":{"code":"MO","description":"Monday","isSet":false},"nr":1},
{"value":{"code":"TU","description":"Tuesday","isSet":true},"nr":2}
]

value的问题也是双引号。删除它们,反序列化工作正常。

<强>更新

如果您不想操纵JSON字符串,可以将其反序列化两次。为此,我更改了类如下:

public class Value
{
    public string Code { get; set; }
    public string Description { get; set; }
    public bool IsSet { get; set; }
}

public class RootObject
{
    public string Value { get; set; }
    public int Nr { get; set; }
}

public class ResultRootObject
{
    public Value Value { get; set; }
    public int Nr { get; set; }
}

然后我可以将其反序列化为ResultRootObject

var rootObjects = JsonConvert.DeserializeObject<List<RootObject>>(badJson, new JsonSerializerSettings());
var result = rootObjects.Select(item => new ResultRootObject
{
    Value = JsonConvert.DeserializeObject<Value>(item.Value),
    Nr = item.Nr
}).ToList();