1

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?

Leonardo
  • 10,737
  • 10
  • 62
  • 155

3 Answers3

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"}}
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
2

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
1

Use simple string formatting or build the json string manually.

var str = String.Format("\"MyRootAttr\": {{ \"value\": \"{{0}}\" }}", MyRootAttr);
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Dexion
  • 1,101
  • 8
  • 14