2

I am trying to get the array directly from the JSON "data" item into an array variable:

string jsonString = "{\"data\":[
                       {\"name\":false,\"number\":true},
                       {\"name\":false,\"number\":false},
                       {\"name\":true,\"number\":false}
                     ]}";

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic jsonObject = serializer.Deserialize(jsonString, typeof(object));

Array jsonArray = jsonObject.data;
// Here error says:
//Cannot implicitly convert type 'System.Collections.Generic.List<object>' to 'System.Array' 

dynamic lastJsonArrayData = jsonArray[jsonArray.Length - 1];
// this is where the error occurs, it says:
//Cannot apply indexing with [] to an expression of type 'Array'

and last thing that I need to do is to convert lastJsonArrayData back to dynamic object but I dont know how.. And I need the last two steps to be performed separately as it stated, it means first to get the array then get the object!! I am a total newbie in C#

EDIT: The real JSON structure is actually more like this:

string jsonString = "{\"firstlevel\":{\"secondlevel\":{\"data\":[
                       {\"name\":false,\"number\":true},
                       {\"name\":false,\"number\":false},
                       {\"name\":true,\"number\":false}
                     ]}}}";
Totallama
  • 418
  • 3
  • 10
  • 26

2 Answers2

1

This seems to work:

var jsonArray = jsonObject.data.ToArray();

(Joel gave me a hint. But he declared Array jsonArray. And it didnt work.)

Totallama
  • 418
  • 3
  • 10
  • 26
0

You might consider creating a class to map the serialised content I meant , you need a create class of

public class Example{
   public string name;
  public string number;
}

and here you need to change it to

var serializer = new JavaScriptSerializer();
                serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
                dynamic jsonObject = serializer.Deserialize(jsonString, typeof(Example));

Hope this reference gives you a better understanding about serialization and desrialization

https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

Deserialize JSON with C#

Hope this helps

Community
  • 1
  • 1
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • I posted here the simplest possible structure of JSON just as an example. But my real JSON contains thousands of items and the structure is far more complicated than this.. – Totallama Oct 16 '16 at 04:52
  • So did you try to change the lines of code i have suggested...Is it still the same problem? – Geeky Oct 16 '16 at 04:54
  • Plus I tried your solution on the simple JSON and still doesnt work. – Totallama Oct 16 '16 at 05:04
  • hey check if this link helps you http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – Geeky Oct 16 '16 at 05:29