Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string with square brackets to json

Tags:

json

c#

I would like to parse this string to Json:

String str="[{\"property\":\"insert_date\",\"direction\":\"ASC\"}]"

I have tried with this:

dynamic myObject=Newtonsoft.Json.JsonConvert.DeserializeObject(str)

but it returns some JArray. I would like to read values simple like:

String dir=myObject.direction;

One option is to parse string and remove square object from string. Than it would work. But i would like to do it on more proper way.

like image 892
Simon Avatar asked Oct 20 '22 00:10

Simon


1 Answers

One way is to create a class and deserialize it as a List<ThatClass>.

For example:

public class Foo
{
    [JsonProperty("property")]
    public string Property { get; set; }
    [JsonProperty("direction")]
    public string Direction { get; set; }
}

and use it like this:

var foos = JsonConvert.DeserializeObject<List<Foo>>(str);
var foo = foos.First();
Console.WriteLine(foo.Direction);

The other way is using dynamic, and simply accessing the first element of the JArray:

String str = "[{\"property\":\"insert_date\",\"direction\":\"ASC\"}]";
dynamic objects = JsonConvert.DeserializeObject<dynamic>(str);
Console.WriteLine(objects[0].direction);
like image 114
Yuval Itzchakov Avatar answered Oct 21 '22 17:10

Yuval Itzchakov