user339160
user339160

Reputation:

issue when converting json string to object

I have the following json string

[["{\"object\":\"user\",\"entry\":[{\"uid\":\"823602904340066\",\"id\":\"823602904340066\",\"time\":1429276535,\"changed_fields\":[\"feed\"]}]}"],["{\"object\":\"user\",\"entry\":[{\"uid\":\"10152579760466676\",\"id\":\"10152579760466676\",\"time\":1429278530,\"changed_fields\":[\"feed\"]}]}"],["{\"object\":\"user\",\"entry\":[{\"uid\":\"10203227586595390\",\"id\":\"10203227586595390\",\"time\":1429278537,\"changed_fields\":[\"feed\"]}]}"],["{\"object\":\"user\",\"entry\":[{\"uid\":\"10203227586595390\",\"id\":\"10203227586595390\",\"time\":1429278521,\"changed_fields\":[\"feed\"]}]}"]]

JsonConvert.DeserializeObject<List<RootObject>>(jsonData);

When rrying to convert this into json object with Netwonsoft.json ,I am get getting error "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Model.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly."

I am using the following classes

public class RootObject
        {
            public List<Entry> entry;
        }

  public class Entry
        {
             public string uid;
             public string id { get; set; }
             public int time { get; set; }
             public List<string> changed_fields { get; set; }
        }

Can some please tell where am i getting it wrong ?

Upvotes: 0

Views: 510

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500873

Your JSON doesn't contain any RootObject objects - it just contains strings. You've got an array of arrays of strings, where each "nested" array just contains a single string, and each string is the JSON representation of a RootObject.

If you can possibly change whatever's producing this, that would be useful. Otherwise, you could use something like (untested):

JArray array = JArray.Parse(json);    
List<RootObject> roots =
   array.Cast<JArray>()
        .Select(innerArray => (string) innerArray[0])
        .Select(text => JsonConvert.DeserializeObject<RootObject>(text))
        .ToList();

I've used two Select calls for clarity - basically one extracts the single string from each nested array, and the other converts it to a RootObject.

Upvotes: 1

spender
spender

Reputation: 120480

So, you have an array of arrays of string. You'll need to 2-step decode.

Step 1:

var stringLists = JsonConvert.DeserializeObject<List<List<string>>>(jsonData);

Step 2:

IEnumerable<RootObject> objects = stringLists.SelectMany(innerList => 
 innerList.Select(jsonString => JsonConvert.DeserializeObject<RootObject>(jsonString))

Upvotes: 0

Related Questions