joe*_*hen 1 c# arrays json.net
我正在使用 NewtosoftJson 生成 json 字符串,并使用表来格式化 json。这是一个简单的键值对列表,如下所示:
public class items
{
private string key = String.Empty;
private string value = String.Empty;
public string Key
{
get
{
return key;
}
set
{
if (value != key)
{
key = value;
}
}
}
public string Value
{
get
{
return value;
}
set
{
if (value != this.value)
{
this.value = value;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当列表被填充然后序列化时,我得到这个 JSON:
"Items": [
{
"Key":"FirstValue",
"Value":"One"
},
{
"Key":"SecondValue",
"Value":"Two"
},
{
"Key":"ThirdValue",
"Value":"Three"
}
]
Run Code Online (Sandbox Code Playgroud)
我需要得到的是:
"customData": {
"items": [
{
"Key":"FirstValue",
"Value":"One"
},
{
"Key":"SecondValue",
"Value":"Two"
},
{
"Key":"ThirdValue",
"Value":"Three"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我尝试创建第二类 CustomData,但不知道如何将原始 JSON 放入第二类!您能否建议我构建第二个类的正确方法以及用于填充它的方法。
您可以创建一个匿名对象并序列化它:
var objContainingItems = ... // your usual code
var customDataObj = new { customData = objContainingItems };
string json = JsonConvert.SerializeObject(customDataObj);
Run Code Online (Sandbox Code Playgroud)
如果您只对序列化感兴趣,这是最方便的解决方案。
如果您还希望能够反序列化它,那么您将需要使用 @William Moore 的答案中指定的类。