5

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.

4
  • 6
    doesn't that just make it myobject[0].direction? Commented Oct 8, 2015 at 9:58
  • 1
    str contains a valid json which upon deserialization will obviously give you array and that's proper. If you want it as single object then you must remove square brackets from source json. I don't know what is going on in your mind. You have already done what you need to, and that is also proper. Commented Oct 8, 2015 at 10:03
  • if it is always single object, try to replace [ and ] and check. Commented Oct 8, 2015 at 10:05
  • If I try myobject[0].direction, i get this: A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll I have found out, It works this way: dynamic myObject = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<object>>(str); Replacing [ and ] would work but i didn't want to parse string as i have described. Commented Oct 8, 2015 at 14:05

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Well I suppose you simply need to do this:

String dir = myobject[0].direction;

It could be the best option I think

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.