我具有以下格式的以下JSON(不是真实数据),我正尝试将其转换为C#等效类。如果您注意到type_1,则type_2可以是任意数字。这很难放在集合中(匿名)。如果我从JSON中删除所有type_1,type_2 ...,则可以轻松地将其转换为类。由于它本质上是动态的,因此很难。
我尝试过http://json2csharp.com/来上课。问题是,它将“类型”转换为成员,这是不正确的,它应该是动态集合或数组。
这个稍微不同的问题
这个问题有两个额外的问题,第一个是“ type_1”元素是动态的,第二个是它们不在列表或数组中。
我无法控制这种JSON格式,这非常令人沮丧。
{
"type_1": {
"@type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI="
},
"type_2": {
"@type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI="
},
"type_3": {
"@type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"type_4": {
"@type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"type_5": {
"@type": "blob",
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
},
"References": {
"blob_1": {
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
"revpos": 1,
"stub": true
},
"blob_2": {
"content_type": "image/jpeg",
"digest": "sha1-rCY0Tk8qRqaLfiQXdxYeX9Y+WMI=",
"revpos": 1,
"stub": true
}
},
"someproperty1": "somevalue1",
"someproperty2": "somevalue2",
"someproperty3": "somevalue3",
"someproperty4": "somevalue4",
"someproperty5": "somevalue5"
}
我在想类似
Filecollection就是那个匿名集合。没有运气;(
public partial class Doc
{
[JsonProperty("references")]
public Dictionary<String, Attachments> Attachments { get; set; }
public List<Dictionary<String, Details>> FileCollections { get; set; }
[JsonProperty("someproperty")]
public String someproperty { get; set; }
[JsonProperty("someproperty2")]
public String someproperty2 { get; set; }
[JsonProperty("someproperty3")]
public String someproperty3 { get; set; }
}
答案 0 :(得分:0)
根据您的评论(希望我理解)...
{
"unknown_a" : {...},
"unknown_b" : {...},
"unknown_c" : {...},
"unknown_d" : {...},
"foo" : true, // known property
"bar" : { // known property
"x" : "xxx",
"y" : "yyy"
}
}
我在想您要一个Dictionary<string, object>
吗?
然后,您可以做一些自己的转换魔术-例如(只是为了使概念更明确)
foreach (d in dictionary)
{
switch (d.Key)
{
case "foo": ... // known property
obj.Foo = (bool)d.Value;
break;
case "bar": ... // known property
obj.Bar = (Bar)d.Value;
break;
default: ... // according to your comments, these are known types
try
{
obj.Files.Add((File)d.Value);
}
catch {...}
break;
}
}