1

I have a problem to extract a JasonObject from a Arry, that contains some objects without a name. Ive got the Array by a batch request form graph.facebook.

[
    {
    "code":200,
    "headers":[{...}],
    "body":"{
        \"id\":\"255572697884115_1\",
        \"from\":{
            \"name\":\"xyzk\",
            \"id\":\"59788447049\"},
        \"message\":\"Hey\",
        \"created_time\":\"2011-11-04T21:32:50+0000\"}"},
    {
    "code":200,
    "headers":[{...}],
    "body":"{
        \"id\":\"255572697884115_2\",
        \"from\":{
             \"name\":\"xyzk\",
             \"id\":\"59788447049\"},
        \"message\":\":P\",
        \"created_time\":\"2012-01-03T21:05:59+0000\"}"}
]

Now I have to read the vaules "message" of the containing objects, but i dont know how i can access the objects in the array. Can anybody give me a helping hand?

I want to use System.Json, additional Newtonsoft.Json.

In Java it is easy to use by GetJsonObject(), but how can i succeed with VSC#? There is an method JsonValueLinqExtensions.ToJsonObject but i dont know, how to use. Could sb give me an example?

Thank you so far,

Dominic

1

1 Answer 1

3

You could parse the JSON into a dynamic using JavaScriptSerializer object e.g.

var serializer = new JavaScriptSerializer();   
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
    Console.WriteLine(item["body"]["message"]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. Your suggest is great but it doesnt work. Converting to dynamic is ok, but i can access body. Compiler says ok, but i get the exception "Object reference not set to an object instance" in line foreach... Do you have any idea?
Sry, the exception is System.Collectios.Generic.Dictionary<string,object> doesnt consist definitions for body
Hey James, thank you for response. The problem is that body is opended by quotes: <"body":"{>. These quotes have to be deletet, i do in following way: dynamic result=JsonArray.Load(s);string st = item.body; dynamic result2 = JsonObject.Parse(st);
@DominicFrank the code provided will work. I was assuming that when you parsed into a dynamic object you could access it like a property. However, if you access it via name it works just fine. The other solution is to actually create a class which represents each "Item" and parse it straight to that which would give you type safety e.g. Item.Body.Message. However, it's whatever you feel is the better solution for you.

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.