C# .NET - deserialize JSON string in c# - Asked By kris kumar on 07-Oct-14 09:40 AM

We are trying to see if we can deserialize the following in c#.  We are trying to send the object as a jsonstring to C# client and at the client side, I tried to deserailise the json string into objects.  I have a Model object that contains a collection of Grid and each grid is another collection of cells.

Model->Grids[collection of Grid]
Grid->DataCellss[collection of  cells]

    public String getModel() {
      String stringWithJSONModel;
      // Create a Model Bean and serialize to JSON  
        ModelBean model = createModel();
        JSONObject modelJSON = new JSONObject(model);
      try {
        System.out.println("Model JSON String Created as follows = " +
      } catch (JSONException jsone) {
        // TODO: Add catch code
      // Create a new Model Object from the JSON String
      stringWithJSONModel = modelJSON.toString();
      return stringWithJSONModel;
   ModelBean createModel() {
      ModelBean model = new ModelBean();
      model.setName("Revenue"); model.setStatus("Submitted");
      Grid grid = new Grid(); grid.setIndex(1);      
      ArrayList<DataCell> cells = new ArrayList<DataCell>();
      DataCell cell = new DataCell(); cell.setValue(110);cell.setRowIndex(1);cell.setColIndex(1);cells.add(cell);
      cell = new DataCell(); cell.setValue(220);cell.setRowIndex(2);cell.setColIndex(2);cells.add(cell);
      ArrayList<Grid> grids = new ArrayList<Grid>(); grids.add(grid);
      return model;

here is the string from the above code passed to c# via web services.



string smdl = myws.getModel();

// string smdl = ss3;

ModelBean mdl = new ModelBean();

MemoryStream msmdl = new MemoryStream(Encoding.Unicode.GetBytes(smdl));

System.Runtime.Serialization.Json.DataContractJsonSerializer serializermdl =

new System.Runtime.Serialization.Json.DataContractJsonSerializer(mdl.GetType());

mdl = serializermdl.ReadObject(msmdl) as ModelBean;

I get the Model object populated with the name and status populated but other objects turned out to be null. Any idea? Please let me know if you know how to deserialize these type of strings.
Santhosh N replied to kris kumar on 08-Jun-09 10:38 PM
You could check here for better understanding of JSON deserializing in c#...


and here for some of the issues discussed...


Re - Ravenet Rasaiyah replied to kris kumar on 07-Oct-14 09:40 AM

Yes C# has support to JSON deseirlization. to this you need follow somesatndards to do this

Check here complete sample and tips by one of the MVP