1

I am trying to parse a JSON obtained from a web API but I do not know how to do it correctly, I am learning C# and I am using JSON.Net, this is my JSON:

{
    "success": true,
    "result": {
        "id": "20429683581",
        "name": "CINEPLEX S.A",
        "Condition": "HABIDO",
        "PLE": "02\/01\/2013",
        "lawyers": [
            {
                "type": "DNI",
                "numdoc": "07871885",
                "name": "PONCE PINTO ALEJANDRO EDUARDO",
                "date": "22\/08\/2000"
            },
            {
                "type": "DNI",
                "numdoc": "09333203",
                "name": "SORIANO BARRANTES JOSE FERNANDO",
                "date": "22\/09\/2008"
            }
        ],
        "workers": [
            {
                "time": "2017-07",
                "service": "8"
            },
            {
                "time": "2018-06",
                "service": "13"
            }
        ]
    }
}

In the example, the API returned 2 "lawyers" and 2 "workers" but this number can vary, they can be 3 or 4 independently (the other section of the json remains constant). With PHP I know very well how to solve this but in C# I do not have much idea, this is the code that I'm using to parse it (I've parsed except "lawyers" and "workers"...)

public class Lawyer
{
    public string type { get; set; }
    public string numdoc { get; set; }
    public string name { get; set; }
    public string date { get; set; }
}

public class Worker
{
    public string time { get; set; }
    public string service { get; set; }
}

public class Result
{
    public string id { get; set; }
    public string name { get; set; }
    public string Condition { get; set; }
    public string PLE { get; set; }
    public List<Lawyer> lawyers { get; set; }
    public List<Worker> workers { get; set; }
}

public class RootObject
{
    public bool success { get; set; }
    public Result result { get; set; }
}

RootObject rootobject;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://www.example.com/api/?get=" + inid);
HttpWebResponse response;

try
{
    response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    {
        var json = reader.ReadToEnd();
        rootobject = JsonConvert.DeserializeObject<RootObject>(json);
    }
    if (rootobject.success == true)
    {
        Console.WriteLine("---------------");
        Console.WriteLine("ID: " + rootobject.result.id);
        Console.WriteLine("NAME: " + rootobject.result.name);
        Console.WriteLine("CONDITION: " + rootobject.result.Condition);
        Console.WriteLine("PLE: " + rootobject.result.PLE);
    }
    else
    {
        Console.WriteLine("---------------");
        Console.WriteLine("NOTHING");
    }
}
catch (Exception)
{
    Console.WriteLine("---------------");
    Console.WriteLine("ERROR");
}

What should I do here? Would I have to use a foreach like in PHP? As I said, the amount of "lawyers" or "workers" can be variable.

Pd: To generate the initial user classes json2csharp.com

Kokox
  • 519
  • 1
  • 9
  • 24
  • 1
    Possible duplicate of [Deserializing JSON data to C# using JSON.NET](https://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net) – Ňɏssa Pøngjǣrdenlarp Aug 28 '18 at 03:56
  • My question focuses on how to count and traverse a JSON for the second time: public List lawyers { get; set; } – Kokox Aug 28 '18 at 04:00
  • have you debugged this and seen what json gets returned in the debugger? I tend to use something like ```var json new WebClient().DownloadString(https://www.example.com/api/?get=" + inid)``` – Keith Nicholas Aug 28 '18 at 04:01
  • oh, its deserialized ok? – Keith Nicholas Aug 28 '18 at 04:02
  • There is no need to manually traverse anything. You can deserialize to a list or array – Ňɏssa Pøngjǣrdenlarp Aug 28 '18 at 04:02
  • The problem is not the API (it works well), what I do not know is how to parse the JSON in second level, I think that I should use "foreach" like PHP but I don't know how to do in C# – Kokox Aug 28 '18 at 04:03

1 Answers1

3

from what I can tell from your comments, you have deserialized this. You are just having trouble traversing the object model which means the whole json.net thing is a bit of a side track, to traverse, just do something like

rootobject.result.lawyers.ForEach(lawyer => Console.WriteLine($"{lawyer.name} {lawyer.type}");

or you can do

foreach(var lawyer in rootobject.result.lawyers) 
{
     Console.WriteLine($"{lawyer.name} {lawyer.type}");
}

or good ol for loops if you wish

for(int i = 0; i<rootobject.result.lawyers.Count; i++)
{
   var lawyer = rootobject.result.lawyers[i];
   // print it...
}
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156