Filipe Ferreira
Filipe Ferreira

Reputation: 23

Deserialize a json file with json.net with int values on structure

Can someone help me to deserialize this JSON file?

{
  "result": "success",
  "records": {
    "504498959": {
      "nif": 504498959,
      "seo_url": "triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda",
      "title": "Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda",
      "address": "Rua Doutor Francisco Noronha, N 31",
      "pc4": "4700",
      "pc3": "355",
      "city": "Braga",
      "activity": "O com\u00e9rcio, importa\u00e7\u00f5es, exporta\u00e7\u00f5es e representa\u00e7\u00f5es de material e equipamento inform\u00e1tico, de telecomunica\u00e7\u00f5es; montagem, instala\u00e7\u00e3o, assist\u00eancia t\u00e9cnica, desenvolvimento de programas inform\u00e1ticos e outros similares.",
      "status": "active",
      "cae": "47781",
      "contacts": {
        "email": null,
        "phone": "253261844",
        "website": null,
        "fax": "253613646"
      },
      "structure": {
        "nature": "UNI",
        "capital": "0.00",
        "capital_currency": "EUR"
      },
      "geo": {
        "region": "Braga",
        "county": "Braga",
        "parish": "S\u00e3o Vicente"
      },
      "place": {
        "address": "Rua Doutor Francisco Noronha, N 31",
        "pc4": "4700",
        "pc3": "355",
        "city": "Braga"
      },
      "racius": "http:\/\/www.racius.com\/triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda\/",
      "alias": "Triworld - Equip. Informaticos e de Telecomunica\u00e7\u00f5es,unipes., Lda",
      "portugalio": "http:\/\/www.portugalio.com\/triworld-equip-informaticos-e-de-telecomunicacoes-unipes\/"
    }
  },
  "nif_validation": true,
  "is_nif": true,
  "credits": {
    "used": "Triworld - Equipamentos Informáticos e de Telecomunicações, Unipessoal Lda",
    "left": {
      "month": 993,
      "day": 99,
      "hour": 9,
      "minute": 0,
      "paid": 0
    }
  }
}

I'm using this code

using Newtonsoft.Json;

public class Rootobject
{
    public string result { get; set; }
    public Records records { get; set; }
    public bool nif_validation { get; set; }
    public bool is_nif { get; set; }
    public Credits credits { get; set; }
}

public class Records
{
    public _504498959 _504498959 { get; set; }
}

public class _504498959
{
    public int nif { get; set; }
    public string seo_url { get; set; }
    public string title { get; set; }
    public string address { get; set; }
    public string pc4 { get; set; }
    public string pc3 { get; set; }
    public string city { get; set; }
    public string activity { get; set; }
    public string status { get; set; }
    public string cae { get; set; }
    public Contacts contacts { get; set; }
    public Structure structure { get; set; }
    public Geo geo { get; set; }
    public Place place { get; set; }
    public string racius { get; set; }
    public string alias { get; set; }
    public string portugalio { get; set; }
}

public class Contacts
{
    public object email { get; set; }
    public string phone { get; set; }
    public object website { get; set; }
    public string fax { get; set; }
}

public class Structure
{
    public string nature { get; set; }
    public string capital { get; set; }
    public string capital_currency { get; set; }
}

public class Geo
{
    public string region { get; set; }
    public string county { get; set; }
    public string parish { get; set; }
}

public class Place
{
    public string address { get; set; }
    public string pc4 { get; set; }
    public string pc3 { get; set; }
    public string city { get; set; }
}

public class Credits
{
    public string used { get; set; }
    public Left left { get; set; }
}

public class Left
{
    public int month { get; set; }
    public int day { get; set; }
    public int hour { get; set; }
    public int minute { get; set; }
    public int paid { get; set; }
}




protected void VerificaNif(object sender, EventArgs e)
{

    Rootobject jsonfileroot = JsonConvert.DeserializeObject<Rootobject>(get_web_content("http://www.triworld.pt/4FPIL83K.json"));

    // need to use "records": { "504498959": { "title": "Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda", on a textbox named Nome.Text

    if (jsonfileroot.result == "success")
    {
        Nome.Text = jsonfileroot.records._504498959.title;
    }
    else
    {
        erro.Text = " Nif is Invalid";
    }
}

but it gives me an NullReferenceException, it can not reach the title.

Could someone help me please? thanks.

Upvotes: 1

Views: 48

Answers (1)

Shiva
Shiva

Reputation: 20935

Here's a working .NetFiddle. It should auto-run. Otherwise just click RUN on that page. See the console output below on that page.

https://dotnetfiddle.net/rMA3Nt

Answer Details:

Change the declaration of your classes as shown below. Once you do that, the following code de-serializes correctly. Here's the output from my console app.

Console App output

enter image description here

Console App Code

class Program
{
    static void Main(string[] args)
    {
        string theJson = "{ \"result\": \"success\", \"records\": { \"504498959\": { \"nif\": 504498959, \"seo_url\": \"triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda\", \"title\": \"Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda\", \"address\": \"Rua Doutor Francisco Noronha, N 31\", \"pc4\": \"4700\", \"pc3\": \"355\", \"city\": \"Braga\", \"activity\": \"O com\u00e9rcio, importa\u00e7\u00f5es, exporta\u00e7\u00f5es e representa\u00e7\u00f5es de material e equipamento inform\u00e1tico, de telecomunica\u00e7\u00f5es; montagem, instala\u00e7\u00e3o, assist\u00eancia t\u00e9cnica, desenvolvimento de programas inform\u00e1ticos e outros similares.\", \"status\": \"active\", \"cae\": \"47781\", \"contacts\": { \"email\": null, \"phone\": \"253261844\", \"website\": null, \"fax\": \"253613646\" }, \"structure\": { \"nature\": \"UNI\", \"capital\": \"0.00\", \"capital_currency\": \"EUR\" }, \"geo\": { \"region\": \"Braga\", \"county\": \"Braga\", \"parish\": \"S\u00e3o Vicente\" }, \"place\": { \"address\": \"Rua Doutor Francisco Noronha, N 31\", \"pc4\": \"4700\", \"pc3\": \"355\", \"city\": \"Braga\" }, \"racius\": \"http://www.racius.com/triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda/\", \"alias\": \"Triworld - Equip. Informaticos e de Telecomunica\u00e7\u00f5es,unipes., Lda\", \"portugalio\": \"http://www.portugalio.com/triworld-equip-informaticos-e-de-telecomunicacoes-unipes/\" } }, \"nif_validation\": true, \"is_nif\": true, \"credits\": { \"used\": \"Triworld - Equipamentos Informáticos e de Telecomunicações, Unipessoal Lda\", \"left\": { \"month\": 993, \"day\": 99, \"hour\": 9, \"minute\": 0, \"paid\": 0 } } }";
        Rootobject theRecords = JsonConvert.DeserializeObject<Rootobject>(theJson);
        if (theRecords != null)
        {
            Console.WriteLine("Deserialization succeeded :)");
            if (theRecords.result == "success")
            {
                Console.WriteLine("  # of Records: {0}", theRecords.records.Count);
                int recordCount = 1;
                foreach (var record in theRecords.records)
                {
                    Console.WriteLine("    Record #{0}", recordCount);
                    Console.WriteLine("      Key: {0}", record.Key);
                    Console.WriteLine("        nif: {0}", record.Value.nif);
                    Console.WriteLine("        seo_url: {0}", record.Value.seo_url);
                    Console.WriteLine("        title: {0}", record.Value.title);
                    Console.WriteLine("        address: {0}", record.Value.address);
                    Console.WriteLine("        city: {0}", record.Value.city);
                    Console.WriteLine("        alias: {0}", record.Value.alias);
                    Console.WriteLine("        portugalio : {0}", record.Value.portugalio);
                    recordCount++;
                }
            }
        }
        else
        {
            Console.WriteLine("Deserialization failed :(");
        }

        Console.ReadLine();
    }

}

Here is how you need to modify your class declaration.

Console App Classes

public class Rootobject
{
    public string result { get; set; }
    public Dictionary<int, Location> records { get; set; }
    public bool nif_validation { get; set; }
    public bool is_nif { get; set; }
    public Credits credits { get; set; }
}

public class Location
{
    public int nif { get; set; }
    public string seo_url { get; set; }
    public string title { get; set; }
    public string address { get; set; }
    public string pc4 { get; set; }
    public string pc3 { get; set; }
    public string city { get; set; }
    public string activity { get; set; }
    public string status { get; set; }
    public string cae { get; set; }
    public Contacts contacts { get; set; }
    public Structure structure { get; set; }
    public Geo geo { get; set; }
    public Place place { get; set; }
    public string racius { get; set; }
    public string alias { get; set; }
    public string portugalio { get; set; }
}

public class Contacts
{
    public object email { get; set; }
    public string phone { get; set; }
    public object website { get; set; }
    public string fax { get; set; }
}

public class Structure
{
    public string nature { get; set; }
    public string capital { get; set; }
    public string capital_currency { get; set; }
}

public class Geo
{
    public string region { get; set; }
    public string county { get; set; }
    public string parish { get; set; }
}

public class Place
{
    public string address { get; set; }
    public string pc4 { get; set; }
    public string pc3 { get; set; }
    public string city { get; set; }
}

public class Credits
{
    public string used { get; set; }
    public Left left { get; set; }
}

public class Left
{
    public int month { get; set; }
    public int day { get; set; }
    public int hour { get; set; }
    public int minute { get; set; }
    public int paid { get; set; }
}

Key Things To Note:

The RootObject has a Dictionary<int, Location> records that will have the int value as key and the object contained inside as a Location object.

If the int values could be duplicate in your final json, then change it to a List<NameValuePair<string,Location>>

The numeric key for the records entity will be the key of the Dictionary object inside the RootObject. The value will be the class called Location (I gave it that name, maybe something is more appropriate. You would know best.

Upvotes: 2

Related Questions