Deserialize JSON Array in an Object Array

16

Good afternoon, I decided to ask because I have been caught in this for 3 days and no matter how much I have searched, I have not 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'm using Json.net (newtonsoftjson) to convert each "Game" contained in Json to an object with the same attributes as in Json, but I get a lot of errors. I'm currently converting this way:

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

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

However, I get the following error:

  

It is not possible to convert an object of type Newtonsoft.Json.Linq.JValue in type Newtonsoft.Json.Linq.JObject

and when I try to put the JValue type inside the foreach, I get the error:

  

Error converting value 123 to type 'WpfApplication1.Game'.Path', line1 position 3.

Sorry for any error while posting this way, but I've already reviewed the Newtonsoft documentation, I've reviewed google and nothing helped.

    
asked by anonymous 29.01.2016 / 18:44

3 answers

15

First a few points, and finally 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 this way:

    { "games": []}

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

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

For your deserialization to succeed, 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 listagames object will have its games property populated with instances of class itemGame .

    
29.01.2016 / 19:25
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 get the answer in json and pass it through the code:

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

If a list comes up use List<ObjJogo>

is in using System.Web.Script.Serialization;

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

    
29.01.2016 / 19:00
3

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

To read using JSON.NET, you must first make the appropriate parsing (i.e., from jsonR to JObject ). Then you can use the ToObject<T> method 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; }
}
    
29.01.2016 / 19:23