Serializing objects with JSON object root

Jul 29, 2009 at 2:11 PM

I have a class like

    class WebServletDeviceInformation
    {
        [JsonProperty(PropertyName = "IMSI")]
        public string Imsi { get; set; }

        [JsonProperty(PropertyName = "IMEI")]
        public string Imei { get; set; }
    }

which i want to serialize to JSON like:

{"deviceinformation":{"IMSI":"262032860005027","IMEI":"4560001"}}

How can i get the deviceinformation root object there without wrapping the object myself in a single property class (kinda stupid) or writing something like:

      var serializer = new JsonSerializer();
      using (var json = new StringWriter())
      {
          using (JsonWriter jsonWriter = new JsonTextWriter(json))
          {
              jsonWriter.WriteStartObject();
              jsonWriter.WritePropertyName("deviceinformation");
              serializer.Serialize(jsonWriter, obj);
              jsonWriter.WriteEndObject();
              return json.ToString();
          }
      }
Coordinator
Jul 30, 2009 at 12:19 AM

You can't. Your solution looks pretty good to me.