Json with C# with node numbered

Asked

Viewed 49 times

1

Does anyone know how to read objects with this file template? It seems that the creator did not use [] for Arrays and also the second node is numbered (not key : value like the json basic).

{  
    "1":{  
        "id":1,
        "nome":"Rodrigo",
        "Apelido":"RK",
        "Fotos":{  
            "120x120":"nome",
            "60x60":"nome",
            "30x30":"nome"
        }
    },
    "2":{  
        "id":1,
        "nome":"Renato",
        "Apelido":"RT",
        "Fotos":{  
            "120x120":"nome",
            "60x60":"nome",
            "30x30":"nome"
        }
    },
    "3":{  
        "id":1,
        "nome":"Luis",
        "Apelido":"LP",
        "Fotos":{  
            "120x120":"nome",
            "60x60":"nome",
            "30x30":"nome"
        }
    }
}

2 answers

2


I would advise the creation of two classes

public class Items: Dictionary<string, Item>
{

}

public class Item
{
    [Newtonsoft.Json.JsonProperty("id")]
    public int Id{ get; set; }
    [Newtonsoft.Json.JsonProperty("nome")]
    public string  Nome { get; set; }
    [Newtonsoft.Json.JsonProperty("Apelido")]
    public string Apelido { get; set; }    
    [Newtonsoft.Json.JsonProperty("Fotos")]        
    public Dictionary<string, string> Fotos { get; set; }
}

and with a simple command using the library Json.NET, make the example below:

string json = System.IO.File.ReadAllText("./base.json");

Items objectJson = Newtonsoft.Json.JsonConvert.DeserializeObject<Items>(json);

this variable objectJson now he’s a class guy Items just access the keys and value easily to fetch the information contained in the file json.

  • OK! It worked out! Thank you very much!

  • If it is the solution can you accept it as the answer? @Rodrigokönig

  • 1

    Sure! How do I do that? I’m new here!

0

Actually in the json is always the combination chave:valor

Note that the node you say is numbered is a string: "1":{

So the access form is the default:

string id = Convert.ToString(jsonObj["1"]["id"]);
string nome = Convert.ToString(jsonObj["1"]["nome"]);
  • But would I have to loop to read the 2nd node? Because it has random numbers. From 1 to 5000. You can’t manually recover.

Browser other questions tagged

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