1

I am trying to figure out a way to deserialize Json object of type:

{
     "0": { "course": { name: "<cource name", .... } },
     "1": { "course": { name: "<cource name", .... } },
     "success": true
}

into

List<Course>

where

public class Course 
{
    public string Name { get; set; }
}

The problem is that it is not a "named" array and it has indexes in place of property name. This array is dynamic, that is contain many elements, i.e. "0", "1", "2", etc. Is there an easy way to deserialize it via Json.NET. I can obviously deserialize it to dynamic object and then create a a for loop and lookup index one by one, but I thought Json.Net might have something more elegant for this.

2
  • Start coding the loop. Commented Apr 27, 2015 at 3:06
  • Since the indices could vary from any range.. you probably should use dynamic with loop.. Commented Apr 27, 2015 at 3:08

2 Answers 2

4

You can use Json.Net's Linq-to-Json API (JObjects) to parse the JSON and get it into the structure you want. For example:

string json = @"
{
     ""0"": { ""course"": { name: ""Foo"" } },
     ""1"": { ""course"": { name: ""Bar"" } },
     ""success"": true
}";

JObject jo = JObject.Parse(json);
List<Course> courses = jo.Properties()
    .Where(p => p.Name != "success")
    .Select(p => p.Value["course"].ToObject<Course>())
    .ToList();

foreach (Course c in courses)
{
    Console.WriteLine(c.Name);
}

Output:

Foo
Bar

Fiddle: https://dotnetfiddle.net/cpN2DE

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I have already done something similar. I deserialized to JObject, then put a while loop to keep iterating until no more indexes left and deserialize each value to Course. Regardless, it is similar to your, so marking as an answer.
1

Try making a dictionary for the course objects:

public class MyData{
  [JsonProperty("success")]
  public bool Success {get;set;}

  public Dictionary<string,Course> Courses{get; private set;}

  public MyData(){
    Courses = new Dictionary<string, Course>();
  } 
}

if your index is an integer you can do Dictionary<int, Course>

2 Comments

The problem with this is the stupid "success" property that doesn't fit
did you try the exact structure I suggested here? Newtonsoft Json deserializer has the ability to assign unassigned tags into catch-all dictionaries, it should work, maybe with some tweaking

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.