How to custom map property to JSON

对着背影说爱祢 提交于 2019-12-08 07:07:54

问题


Desired JSON:

"MyRootAttr": {
    "value": "My Value"
}

Property definition in the class:

public string MyRootAttr { get; set; }

So, the question is, without defining a new class, with a single string property, how can i achieve the JSON I want?


回答1:


If you don't want to alter your class structure, you can use a custom JsonConverter to achieve the result you want:

class WrappedStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string s = (string)value;
        JObject jo = new JObject(new JProperty("value", s));
        jo.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        return (string)jo["value"];
    }
}

To use it, add a [JsonConverter] attribute to your string property like this:

class Foo
{
    [JsonConverter(typeof(WrappedStringConverter))]
    public string MyRootAttr { get; set; }
}

Round-trip demo here: https://dotnetfiddle.net/y1y5vb




回答2:


As I mentioned in my comment, an anonymous type could help accomplish this:

var myObj = new { MyRootAttr = new { value = "My Value" } };
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(myObj); //{"MyRootAttr":{"value":"My Value"}}

With Json.net:

string json = JsonConvert.SerializeObject(myObj); //{"MyRootAttr":{"value":"My Value"}}



回答3:


Use simple string formatting or build the json string manually.

var str = String.Format("\"MyRootAttr\": {{ \"value\": \"{{0}}\" }}", MyRootAttr);


来源:https://stackoverflow.com/questions/37418649/how-to-custom-map-property-to-json

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