0

With the following REST service response:

"[{\"field1\":\"Eva\",\"field2\":\"29\",\"field3\":false},{\"field1\":\"Karen\",\"field2\":\"32\",\"field3\":false}]"

I´m getting an error when trying to deserialize it (ERROR: line 1, position 117)

public class Person
{
   public string field1 { get; set; }
   public string field2 { get; set; }
   public string field3 { get; set; }
}

Task<string> jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
var model = JsonConvert.DeserializeObject<List<Person>>(jsonString.Result);

Could help me somebody please?

Thanks in advance.

Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
Jose
  • 55
  • 8
  • 1
    If you're **really** getting that response, it's been double-encoded. Someone's taken a structure and converted it to a JSON string via a JSON serializer, then taken that string and run it through a JSON serializer **again**. – T.J. Crowder Aug 27 '16 at 13:19

3 Answers3

1

You need to use JToken to parse your response. After then, you should be able to deserialize it. Here below is a working example:

public class Person
{
   public string field1 { get; set; }
   public string field2 { get; set; }
   public string field3 { get; set; }
}

var response = "[{\"field1\":\"Eva\",\"field2\":\"29\",\"field3\":false},{\"field1\":\"Karen\",\"field2\":\"32\",\"field3\":false}]";
JToken json = JToken.Parse(response);
var model = json.ToObject<List<Person>>();
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
0

"field3" has to be bool not string.

public bool field3 { get; set; }

If that does not work, try to use this structure, since it seems to be the right structure based on the json that you have provided:

public class Rootobject
{
    public Person[] Person { get; set; }
}

public class Person
{
    public string field1 { get; set; }
    public string field2 { get; set; }
    public bool field3 { get; set; }
}
Ashkan S
  • 10,464
  • 6
  • 51
  • 80
0

Thanks everybody for your responses. Finally, the problem was related with the kind of type used on sending the info in the REST service: string instead of stream. Now works great! If can helps anybody, this is the code on server side:

JsonString = JsonConvert.SerializeObject(ds.Tables[0], Formatting.Indented);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
                return new MemoryStream(Encoding.UTF8.GetBytes(JsonString));

@Oluwafemi is really needed using?:

JToken json = JToken.Parse(response);

Thanks.

Jose
  • 55
  • 8
  • Read this for more info on why it is needed: https://stackoverflow.com/questions/38211719/json-net-why-use-jtoken-ever – Oluwafemi Aug 05 '17 at 09:29