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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Findus
  • 303
  • 1
  • 4
  • 17
  • 1
    check following links they might help you. http://stackoverflow.com/questions/2859753/what-is-simpliest-c-sharp-function-to-parse-json-string-into-object http://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object – Geethanga Sep 06 '12 at 14:36

1 Answers1

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"]);
}
James
  • 80,725
  • 18
  • 167
  • 237
  • 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? – Findus Sep 06 '12 at 18:17
  • Sry, the exception is System.Collectios.Generic.Dictionary doesnt consist definitions for body – Findus Sep 06 '12 at 19:09
  • 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); – Findus Sep 07 '12 at 08:04
  • @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. – James Sep 07 '12 at 08:26