views:

307

answers:

3

Hello, I have an object in Javascript that looks like this

function MyObject(){
  this.name="";
  this.id=0;
  this.....
}

I then stringify an array of those objects and send it to an ASP.Net web service.

At the webservice I want to unserialize the JSON string so I can deal with the data easily in C#. Then, I want to send an array of objects of the same Javascript type(same field names and everything) back to the client. The thing I'm not understanding is how to serialize say this class:

class MyObject{
  public string Name;
  public int ID;
}

so that the JSON is the same as the above javascript object. And also how to unserialize into the C# MyObject class.

How would I do this easily? I am using Netwonsoft.Json.

Is there some way to turn a JSON string into a List or Array of an object?

A: 

You can try the DataContractJsonSerializer Rick Strahl Has a fairly good example.

You tell the serializer the type that you are serializing to and you can decorate the class properties telling them to expect a different name.

As an example:

class MyObject{ 
  [DataMember(name="name")]
  public string Name;
  [DataMember(name="id")] 
  public int ID; 
} 

EDIT: Use

using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
     ser = new DataContractJsonSerializer(typeof(MyObject)); 
     MyObject obj = ser.ReadObject(ms) as MyObject;

     int myObjID = obj.ID;
     string myObjName = obj.Name;
}
Patrick
+4  A: 

with json.net you can use the JsonPropertyAttribute to give your serialized properties a custom name:

class MyObject{

    [JsonProperty(PropertyName = "name")]
    public string Name;

    [JsonProperty(PropertyName = "id")]
    public int ID;
}

you can then serialize your object into a List<> like so:

var list = new List<MyObject>();
var o = new MyObject();
list.Add(o);
var json = JsonConvert.SerializeObject(list);

and deserialize:

// json would look like this "[{ "name":"", "id":0 }]"
var list = JsonConvert.DeserializeObject<List<MyObject>>(json);
ob
Great answer considering it uses Netwonsoft.Json.
Patrick
A: 

One thing the WebMethod gives you back is a "d" wrapper which I battled with for hours to get around. My solution with the Newtonsoft/JSON.NET library is below. There might be an easier way to do this I'd be interested to know.

public class JsonContainer
{
    public object d { get; set; }
}

public T Deserialize<T>(string json)
{
    JsonSerializer serializer = new JsonSerializer();

    JsonContainer container = (JsonContainer)serializer.Deserialize(new StringReader(json), typeof(JsonContainer));
    json = container.d.ToString();

    return (T)serializer.Deserialize(new StringReader(json), typeof(T));
}
Chris S