0

I work with an api, that returns a json formatted resultset of a database query. I have an equivalent object or "model" for the results. What is the best way to convert the json string into a list of this object?

Of course there are many threads about this, but no one fits my needs properly.

One of the solutions I've found was this:

var jobj = (JObject)JsonConvert.DeserializeObject(json);
var items = jobj.Children()
    .Cast<JProperty>()
    .Select(j => new
    {
        ID = j.Name,
        Topic = (string)j.Value["Topic_ID"],
        Moved = (string)j.Value["Moved_ID"],
        Subject = (string)j.Value["subject"],
    })
    .ToList();

This seems pretty close to what I need. I need to be able to map the keys/values to the appropriate object attributes, which DOES already exist. So maybe you only need to change a few things to make it work for my object?

PS: I'm using Newtonsoft. Any solution for .NET or Newtonsoft or if needed any other library would be great!

Jim Hewitt
  • 1,726
  • 4
  • 24
  • 26
Cutaraca
  • 2,069
  • 3
  • 14
  • 21
  • If the json properties and the final object properties don't match exactly, I would create a DTO (DataTransferObject) to match the json, load into the DTO from json, then convert the DTO to the final object. An extra step, but a bit cleaner (a tool like AutoMapper can help a bit here as well) – jleach Jan 02 '17 at 16:13
  • You may want to say why none of the existing threads match your problem. Reading your question I would guess its because your model object member names do not match those of the JSON object, but its not clear that's the case. – sebf Jan 02 '17 at 17:26
  • 1
    Possible duplicate of [Deserializing JSON data to C# using JSON.NET](http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net) – Dour High Arch Jan 02 '17 at 19:40
  • *Of course there are many threads about this, but no one fits my needs properly.* In that case, please share the JSON and the model to which you are trying to deserialize the JSON, and we may be able to suggest something. Without a [mcve] we're just guessing. – dbc Jan 02 '17 at 23:20

3 Answers3

1

I have recently been consuming data from a WebApi and i have been using the following code to convert the json object to an object to work with:

using (var client = new HttpClient())
{
    var response = client.GetAsync(apiUri).Result;

    // For single objects.
    MyObject data = response.Content.ReadAsAsync<MyObject>().Result;

    // For an array of objects
    IEnumerable<MyObject> data = response.Content.ReadAsAsync<IEnumerable<MyObject>>().Result;
}

Hope this helps.

0

OK, so you have something like this:

public class MyObject
{
   public int ID {get; set;}
   public string Topic {get; set;}
   public string Subject {get; set;}
}

And you want to instantiate an array of MyObjects with the properties coming from your JSON?

In that case you're just a bout there - you're currently creating a dynamic object with the same properties as MyObject, right? So all you need to do is create an actual MyObject instead:

.Select(j => new **MyObject()**
{
    ID = j.Name,
    Topic = (string)j.Value["Topic_ID"],
    Moved = (string)j.Value["Moved_ID"],
    Subject = (string)j.Value["subject"]
})

Note that if your json property names exactly match your C# ones (including case), you can do this as a one-liner with NewtonSoft: http://www.newtonsoft.com/json/help/html/SerializingJSON.htm. But to use that method you'd have to have an intermediate C# class to match your JSON, and then automap (or manually convert) those to MyObjects. Or you'd have to make sure your json and c# properties match exactly. But you're already very close to a quicker (though some would argue less elegant) solution.

Edward D
  • 521
  • 3
  • 9
  • Thanks for you reply. I get a System.InvalidCastException on var jobj = (JObject)JsonConvert.DeserializeObject(json); (using Newtonsoft.Json.Linq) When I change JObject to Brand, it complains about the undefined Children() method. Maybe I should just adjust the column names in the database... – Cutaraca Jan 02 '17 at 17:10
  • I've found a clean easy way: This questioner has the same situation as you, I think, and the first answer looks good: http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net Basically, you use the generic JsonConvert.DeserializeObject(string json) to deserialize, and you decorate your class's properties with the names of the json propertes, as per the asker's code -- [JsonProperty(PropertyName = "username")] – Edward D Jan 02 '17 at 19:05
0

Why aren't you deserializing the json into the object type directly? you can do it like this...

var obj = (YourType)JsonConvert.DeserializeObject(
                   json,
                   typeof(YourType),
                   new JsonSerializerSettings()
                   {
                       TypeNameHandling = TypeNameHandling.Auto,
                       MissingMemberHandling=MissingMemberHandling.Ignore
                   });

or am I missing something in the question?