Using JSON.Net to write a property name

妖精的绣舞 提交于 2019-12-10 02:29:18

问题


I am using JSON.net to write some json in C#. I can produce JSON like this

{
    "id": "234",
    "name": "abc"
}

What i would like to do is get is this

 {
    "DATA": {
        "id": "234",
        "name": "abc"
    }
}

Here is the json.net code i'm using

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    JsonWriter jsonWriter = new JsonTextWriter(sw);
    jsonWriter.Formatting = Formatting.Indented;



        jsonWriter.WriteStartObject();                 
            jsonWriter.WritePropertyName("id");
            jsonWriter.WriteValue("234");
            jsonWriter.WritePropertyName("name");
            jsonWriter.WriteValue("abc");
        jsonWriter.WriteEndObject();

can you suggest how to add the 'DATA' section to it?


回答1:


Make the root object, then write the property name "DATA", then write the object you just wrote:

jsonWriter.WriteStartObject();
    jsonWriter.WritePropertyName("DATA");
    jsonWriter.WriteStartObject();
        jsonWriter.WritePropertyName("id");
        jsonWriter.WriteValue("234");
        jsonWriter.WritePropertyName("name");
        jsonWriter.WriteValue("abc");
    jsonWriter.WriteEndObject();
jsonWriter.WriteEndObject();


来源:https://stackoverflow.com/questions/7327853/using-json-net-to-write-a-property-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!