问题
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