-1

I want my Json data to look like this:

 {"Person": {
    "PersonId": "1"
    "Name":"Brad",
    "Age":"45",
   ...
  }

where "Person" would be the type of Object returned.

When I see XML format it always returns data with Object Type specified

<Person>
     <PersonId>1</PersonId>
     <Name>Brad</Name>
     <Age>45</Age>
</Person>
 Where Person is type of Object.

so is there any way we get the Json data as specified in the format above ?

subi_speedrunner
  • 901
  • 3
  • 9
  • 17

1 Answers1

0

May be:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonController : ApiController
{
    /*{"ArrayOfPerson":[{"PersonId":1,"Name":"Brad","Age":45},{"PersonId":2,"Name":"Mary","Age":30}]}*/
    [HttpGet]
    public HttpResponseMessage Get()
    {
        Person person1 = new Person { PersonId = 1, Name = "Brad", Age = 45 };
        Person person2 = new Person { PersonId = 2, Name = "Mary", Age = 30 };

        IEnumerable<Person> data = new List<Person> { person1, person2 };
        JToken json = MyHelper.ToJson(data);
        return Request.CreateResponse<JToken>(json);
    }

    //{"Person":{"PersonId":1,"Name":"Brad1","Age":45}} 
    [HttpGet]
    public HttpResponseMessage Get(int id)
    {
        Person data = new Person { PersonId = id, Name = string.Concat("Brad", id), Age = 45 };
        JToken json = MyHelper.ToJson<Person>(data);
        return Request.CreateResponse<JToken>(json);
    }
}


public static class MyHelper
{
    public static JToken ToJson<T>(T source)
    {
        JObject result = new JObject();

        Type type = typeof(T);
        string key = type.Name;
        if (typeof(IEnumerable).IsAssignableFrom(type))
            key = string.Format("ArrayOf{0}", GetEnumeratedType(type).Name);

        JToken value = (source != null) ? JToken.FromObject(source) : JValue.CreateNull();//Newtonsoft.Json 6.0.6
        result.Add(key, value);
        return result;
    }

    /// <summary>
    /// Use http://stackoverflow.com/questions/4129831/how-do-i-get-the-array-item-type-from-array-type-in-net
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static Type GetEnumeratedType(Type type)
    {
        // provided by Array
        var elType = type.GetElementType();
        if (null != elType) return elType;

        // otherwise provided by collection
        var elTypes = type.GetGenericArguments();
        if (elTypes.Length > 0) return elTypes[0];

        // otherwise is not an 'enumerated' type
        return null;
    }
}
Oleg Oyun
  • 1
  • 1