0

I am trying to parse a JSON array that looks something like this:

{
  "chatName": "Test",
  "users": [
    "User1",
    "User2"
  ],
  "someBooleanValue": true,
  "someObjects": {
    "object1": "someObjectValue1",
    "object2": "someObjectValue2",
    ...
  }
}

Is there a way to parse the someObjects array of objects, when I don't know how many objects the array will have before I start processing the JSON file?

All the parsing is done using Json.NET.

BWA
  • 5,672
  • 7
  • 34
  • 45

3 Answers3

1

You can use dynamic for someObjects. Code can look like:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
{
    public string chatName { get; set; }
    public List<string> users { get; set; }
    public bool someBooleanValue { get; set; }
    public dynamic someObjects { get; set; }
}

public class Program
{
    static public void Main()
    {
        string j = "{\"chatName\": \"Test\",\"users\": [\"User1\",\"User2\"],\"someBooleanValue\": true,\"someObjects\": {\"object1\": \"someObjectValue1\",\"object2\": \"someObjectValue2\"}}";

        RootObject ro = JsonConvert.DeserializeObject<RootObject>(j);

        Console.WriteLine(ro.someObjects.object1);
    }    
}
BWA
  • 5,672
  • 7
  • 34
  • 45
  • Is there a way to iterate through someObject's properties and get it's value (such as someObjectValue1), since I don't know the name of each individual property (object1 and object2 names change often). – Daniel Zikmund Jul 26 '16 at 10:46
  • Look at this: http://stackoverflow.com/questions/2594527/how-do-i-iterate-over-the-properties-of-an-anonymous-object-in-c – BWA Jul 26 '16 at 11:07
0

someObjects needs to be deserailized either to an Object (class) or a JObject (C# json) or to some kind of Dictionary.

You can Deserialize the json using json.net's method: JsonConvert.DeserializeObject<T>.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
-1

you can use JavaScriptSerializer().Serialize Converts an object to a JSON string.

string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(object name);

similarly to deserialize you can use Deserialize function

string json = "{\"chatName\": \"Test\",\"users\": [\"User1\",\"User2\"],\"someBooleanValue\": true,\"someObjects\": {\"object1\": \"someObjectValue1\",\"object2\": \"someObjectValue2\"}}";

Classname objectname = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json);