I can not parse json with brackets in C #

-2

I'm using the Newtonsoft.Json.Linq library to parse json in C #. So far it worked beauty, when I have a json string like this:

{
    'chave':'valor'
}

But when I have a json like this:

[
    {
        'chave':'valor'
    },
    {
        'chave':'valor',
        'outrachave':'outrovalor'
    }
]

PS: This json is coming from the mysql database, it has been converted to the html URI format, by javascript, in a mysql column, I connect to the database with C #, I retrieve this value and use the following

string json = Uri.UnescapeDataString(pedido).ToString();

So I get json, and trying to parse it like this

JToken result = JObject.Parse(json); 

And the error is as follows: Error reading JObject from JsonReader item is not an object

Does this library not accept even when it's bracket?

    
asked by anonymous 16.05.2018 / 17:22

2 answers

0

It's because you're trying to convert a collection to a single object.

When Json has brackets, the output object must be a collection.

JToken[] result = JObject.Parse(json); 
    
17.05.2018 / 06:16
0

When json is between [] means that it is a array , see here

for this folder make Deserialize of a list

Class with the properties of json :

public class Dados
{
    public string chave { get; set; }
    public string outrachave { get; set; }
}

Deserialize of json

string json = "[{'chave':'valor'},{'chave':'valor','outrachave':'outrovalor'}]";
List<Dados> itens = JsonConvert.DeserializeObject<List<Dados>>(json);

I put it in .Net Fiddle for reference

    
18.05.2018 / 20:31