使用Json.NET反序列化键值对数组 [英] Deserialize array of key value pairs using Json.NET
问题描述
给出以下json:
[ {"id":"123", ... "data":[{"key1":"val1"}, {"key2":"val2"}], ...}, ... ]
这是一棵更大的树的一部分,如何将"data"属性反序列化为:
that is part of a bigger tree, how can I deserialize the "data" property into:
List<MyCustomClass> Data { get; set; }
或
List<KeyValuePair> Data { get; set; }
或
Dictionary<string, string> Data { get; set; }
使用Json.NET?无论哪种版本都可以(尽管我更喜欢MyCustomClass的列表).我已经有一个包含其他属性的类,如下所示:
using Json.NET? Either version will do (I prefer List of MyCustomClass though). I already have a class that contains other properties, like this:
public class SomeData
{
[JsonProperty("_id")]
public string Id { get; set; }
...
public List<MyCustomClass> Data { get; set; }
}
其中"MyCustomClass"将仅包括两个属性(键和值).我注意到有一个KeyValuePairConverter类听起来像它可以满足我的需要,但是我找不到如何使用它的示例.谢谢.
where "MyCustomClass" would include just two properties (Key and Value). I noticed there is a KeyValuePairConverter class that sounds like it would do what I need, but I wasn't able to find an example on how to use it. Thanks.
推荐答案
最简单的方法是将键-值对数组反序列化为IDictionary<string, string>
:
The simplest way is deserialize array of key-value pairs to IDictionary<string, string>
:
public class SomeData
{
public string Id { get; set; }
public IEnumerable<IDictionary<string, string>> Data { get; set; }
}
private static void Main(string[] args)
{
var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
var obj = JsonConvert.DeserializeObject<SomeData>(json);
}
但是如果您需要将其反序列化到您自己的类中,它可能看起来像这样:
But if you need deserialize that to your own class, it can be looks like that:
public class SomeData2
{
public string Id { get; set; }
public List<SomeDataPair> Data { get; set; }
}
public class SomeDataPair
{
public string Key { get; set; }
public string Value { get; set; }
}
private static void Main(string[] args)
{
var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
var rawObj = JObject.Parse(json);
var obj2 = new SomeData2
{
Id = (string)rawObj["id"],
Data = new List<SomeDataPair>()
};
foreach (var item in rawObj["data"])
{
foreach (var prop in item)
{
var property = prop as JProperty;
if (property != null)
{
obj2.Data.Add(new SomeDataPair() { Key = property.Name, Value = property.Value.ToString() });
}
}
}
}
看到我知道Value
是string
并调用ToString()
方法,可能还有另一个复杂的类.
See that I khow that Value
is string
and i call ToString()
method, there can be another complex class.
这篇关于使用Json.NET反序列化键值对数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!