Deserialize JSON Array in an Object Array

Asked

Viewed 8,395 times

16

Good afternoon, I decided to ask because I’ve been holding on to this for three days and as much as I’ve looked, I haven’t found a solution to my problem. Access a Web Service via C#, Httpclient, and get a Json in the following format:

{
    "games": [
        {
            "IdJogo": "1",
            "Titulo": "No Man's Sky",
            "DtaLancamento": "Junho 2016",
            "ResumoBR": "Em No Man's Sky  você assume o papel de um     explorador planetário com uma nave espacial, permitindo-lhes explorar a     superfície de vários planetas e interagir com a flora e fauna, e viajar pelo espaço, entrar em combate com forças inimigas e viajar a outros planetas.",
            "NomeImg": "NoManSky.jpg"
        },
        {
            "IdJogo": "2",
            "Titulo": "Starbound",
            "DtaLancamento": "Dezembro 2013",
            "ResumoBR": "Starbound é um sandbox/open world, nele você vive     em uma espaçonave e pode explorar diferentes mundos, sistemas solares, galáxias, etc. As possibilidades são praticamente infinitas!",
            "NomeImg": "Starbound.jpg"
        }

I am using Json.net (newtonsoftjson) to convert each "Game" contained in Json to a object with the same attributes existing in Json, but I get the most diverse errors. Currently, I do the conversion in this way:

string jsonR = resposta.Content.ReadAsStringAsync().Result;                    

foreach (JObject elemento in jsonR)
{
    Game game = JsonConvert.DeserializeObject<Game>(elemento.ToString());  
} 

However, the following error returns to me:

It is not possible to convert an object of type Newtonsoft.Json.Linq.Jvalue into type Newtonsoft.Json.Linq.Jobject

and when I try to put as type Jvalue inside the foreach, I obey the error:

Error Converting value 123 to type 'Wpfapplication1.Game'. Path ",line1 position 3.

I’m sorry for any mistake in posting this way, but I’ve reviewed the Newtonsoft documentation, I’ve reviewed the Google and nothing has helped me.

  • ...<Game>(elemento.ToString());? This is how it should be?

  • When I shoot Tostring I already get an error in that line saying that you can’t convert from Newtonsoft.Json.Linq.Jobject to string..

  • The Deserializeobject method accepts a Json string as parameter.

  • If you already have one JObject, you can call the method ToObject<T> instead of converting it to string and then converting that string to your object.

3 answers

15


First a few points, and at the end a solution.

  • Your JSON is the representation of an object that has a property, games, which in turn is a collection. Simplified, it can be expressed in this way:

    { "games": []}

  • This collection consists of simple objects (a relation of properties with primitive values):

    {"IdJogo": "","Titulo": "","DtaLancamento": "","ResumoBR": "","NomeImg": ""}

In order for your deserialization to occur successfully, you need to create classes that represent these entities:

public class listaGames () {
    public List<itemGame> games {get; set;}
}

public class itemGame () {
    public string IdJogo {get;set;}
    public string Titulo {get; set;}
    public string DtaLancamento {get; set;}
    public string ResumoBR {get; set;}
    public string NomeImg {get; set;}
}

With these present structures, you can now deserialize JSON:

string jsonR = resposta.Content.ReadAsStringAsync().Result;                    

listaGames listagames = JsonConvert.DeserializeObject<listaGames>(jsonR);  

As a result, the object listagames will have your property games populated with instances of the class itemGame.

  • Putz, thank you so much, man. If I could I’d give you a hug.

  • @Fumegz Always a pleasure to help, I’m glad it worked. =)

7

Create the object with the desired fields type:

struct ObjJogo
{
   public string IdJogo        { get; set; }
   public string Titulo        { get; set; }
   public string DtaLancamento { get; set; }
//-- e outros...
}

Then take the json response and pass it through the code:

JavaScriptSerializer js = new JavaScriptSerializer();
ObjJogo jsonData = js.Deserialize<ObjJogo>(RespostaWS);

If you see a list use List<ObjJogo>

this in the using System.Web.Script.Serialization;

I hope it helps, I had a problem like this and so I solved it.

  • It helped and a lot, I saw the problem from another angle. VLW!

  • No, that’s why it’s always a pleasure to be able to help

3

The first foreach is trying to convert the string jsonR in a JValue using the implicit converter. You end with a JSON string, not an object, which is what you need.

To read using JSON.NET, you first need to make the appropriate Parsing (i.e., from jsonR for a JObject). Then you can use the method ToObject<T> to convert the JSON object to its type, as in the example below.

class Program
{
    static void Main()
    {
        var jo = JObject.Parse(jsonR);
        var games = jo["games"].ToObject<Game[]>();
        foreach (var game in games)
        {
            Console.WriteLine(game);
        }
    }

    const string jsonR = @"{
        ""games"": [
            {
                ""IdJogo"": ""1"",
                ""Titulo"": ""No Man's Sky"",
                ""DtaLancamento"": ""Junho 2016"",
                ""ResumoBR"": ""Em No Man's Sky  você assume o papel de um explorador planetário com uma nave espacial, permitindo-lhes explorar a superfície de vários planetas e interagir com a flora e fauna, e viajar pelo espaço, entrar em combate com forças inimigas e viajar a outros planetas."",
                ""NomeImg"": ""NoManSky.jpg""
            },
            {
                ""IdJogo"": ""2"",
                ""Titulo"": ""Starbound"",
                ""DtaLancamento"": ""Dezembro 2013"",
                ""ResumoBR"": ""Starbound é um sandbox/open world, nele você vive em uma espaçonave e pode explorar diferentes mundos, sistemas solares, galáxias, etc. As possibilidades são praticamente infinitas!"",
                ""NomeImg"": ""Starbound.jpg""
            }
        ]
    }";
}

public class Game
{
    public string IdJogo { get; set; }
    public string Titulo { get; set; }
    public string DtaLancamento { get; set; }
    public string ResumoBR { get; set; }
    public string NomeImg { get; set; }
}
  • Thank you so much! Now I have two solutions! Both tested and approved!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.