从JSON数组中提取对象到列表 [英] Extract objects from JSON array to list

查看:124
本文介绍了从JSON数组中提取对象到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working in C# code and the JSON service result I get looks like this:

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

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

I want to work with a list of deserialized value objects from this array. But my impression is that my code is a bit cumbersome.

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

是否正在选择字符串并将其解析为对象,然后真正将其转换为执行此操作的方法?还是可以更有效地做到这一点?

Is selecting strings and parsing them as objects which then get casted really the way to do this? Or can this be done more efficient?

推荐答案

使用以下类:

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字符串,如下所示:

and then deserialize your JSON string like this:

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

需要不转义JSON字符串:

The JSON string needs to be unescaped:

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

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

Also the issue with the value is the double quotes. Remove them, and the deserialization works fine.

更新

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

If you do not want to manipulate the JSON string you can deserialize it twice. For this, I changed the classes like follows:

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:

Then I could deserialize it to 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();

这篇关于从JSON数组中提取对象到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆