I can’t parse json with brackets in c#

Asked

Viewed 668 times

-2

I am using the Newtonsoft.Json.Linq library to parse json in c#. Until now it worked beauty, when I have a string json 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 comes converted into html URI format, by javascript, in a mysql column, I connect in the database with c#, recover this value and use the following

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

So I pick up the json, and try 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 is square bracket?

  • Ever tried to "escape", put a ' ' before, like this ' \[ ' ?

  • Hi, I added some information to the question....

  • That I knew, json unaccepted ' (single quotes) and yes " (double quotes). Ides always accuse this as a mistake.

2 answers

1

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

for that pasta do Deserialize from 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 in the .Net Fiddle for reference

0

It is because you are trying to convert a collection into a single object.

When Json has brackets, it is necessary for the output object to be a collection.

JToken[] result = JObject.Parse(json); 
  • I understood your idea, but the visual studio said that it is not possible to converver Jobject in Jtoken[] I think the way is to do a split gambiarra, first remove the [ and ], then split in }, and concateno each of the items with }.

  • Since you are using Newtonsoft, try doing the following: JToken[] result = JsonConvert.DeserializeObject<JToken[]>(json)

Browser other questions tagged

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