给定以下 json:
[ {"id":"123", ... "data":[{"key1":"val1"}, {"key2":"val2"}], ...},... ]
这是更大树的一部分,我如何将数据"属性反序列化为:
List数据{得到;放;}
或
List数据{得到;放;}
或
字典<字符串,字符串>数据{得到;放;}
使用 Json.NET?任何一个版本都可以(尽管我更喜欢 List of MyCustomClass).我已经有一个包含其他属性的类,如下所示:
公共类 SomeData{[JsonProperty("_id")]公共字符串 ID { 获取;放;}...公共列表<MyCustomClass>数据{得到;放;}}
其中MyCustomClass"将仅包含两个属性(键和值).我注意到有一个 KeyValuePairConverter 类听起来可以满足我的需要,但我找不到如何使用它的示例.谢谢.
最简单的方法是将键值对数组反序列化为IDictionary
:
但如果您需要将其反序列化为您自己的类,它可能看起来像这样:
<上一页><代码>公共类 SomeData2{公共字符串 ID { 获取;放;}公共列表<SomeDataPair>数据{得到;放;}}公共类 SomeDataPair{公共字符串密钥 { 获取;放;}公共字符串值 { 获取;放;}}私人静态无效主要(字符串[] args){var json = "{ "id": "123", "data": [ { "key1": "val1" }, { "key2" : "val2"} ] }";var rawObj = JObject.Parse(json);var obj2 = 新的 SomeData2{Id = (string)rawObj["id"],数据 = 新列表看到我知道 Value
是 string
并且我调用 ToString()
方法,可以有另一个复杂的类.
Given the following json:
[ {"id":"123", ... "data":[{"key1":"val1"}, {"key2":"val2"}], ...}, ... ]
that is part of a bigger tree, how can I deserialize the "data" property into:
List<MyCustomClass> Data { get; set; }
or
List<KeyValuePair> Data { get; set; }
or
Dictionary<string, string> Data { get; set; }
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; }
}
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.
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() });
}
}
}
}
See that I khow that Value
is string
and i call ToString()
method, there can be another complex class.
这篇关于使用 Json.NET 反序列化键值对数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!