Nubtacular
Nubtacular

Reputation: 1397

JsonConvert.DeserializeObject cannot deserialize valid JSON

I am perplexed as why the DeserializeObject method cannot deserialize valid JSON:

string source = JsonConvert.SerializeObject(data.Source);
Maintenance ticket_data = JsonConvert.DeserializeObject<Maintenance>(source); //breaks here

When I hit my endpoint, I receive the following:

"ExceptionMessage": "Unexpected character encountered while parsing value: {. Path 'elements', line 21, position 5."

I see where that is happening. Elements has many different attributes, Elements is an array.

In the Maintenance class I have:

public IEnumerable<string> Elements { get; set; }

I used the JSONLint website to make sure source was valid JSON, and it is.

Maintenance Class

Some of the JSON output:

{
  "doc_type": "ticket",
  "updated_date": 12345,
  "ticket_number": "1234",
  "start": 1234,
  "summary": "hello",
  "description": "do stuff",
  "active": true,
  "related_tickets": [],
  "tags": [],
  "elements": [
    {
      "last_updated": 5678,
      "entry_id": null,
      "name": "something",

Any insight as to why I cannot deserialize this JSON would be greatly appreciated.

Upvotes: 0

Views: 2272

Answers (3)

jmesolomon
jmesolomon

Reputation: 563

The error is due to de-serializing a list of objects: elements[{}] to a list of string elements: public IEnumerable<string> Elements

What you can do is create a wrapper Elements class with properties that match the JSON payload like this

 public class Elements {
  public DateTime last_updated {get;set;}
  public int? entry_id {get; set;}
  public string name {get; set;}
 } 

then in your Maintenance.cs you can change the Elements property to

public IEnumerable<Elements> Elements { get; set; }

Also take note of the data type in the JSON payload. Some are not strings. for example is last_updated

Upvotes: 2

Aleš Doganoc
Aleš Doganoc

Reputation: 12092

I think the problem is that your elements is not an array of stings like you defined in the object. From what it looks from the JSON snippet you have objects inside the elements array.

"elements": [{
      "last_updated": 5678,
      "entry_id": null,
      "name": "something",
}

This defines an object with properties last_updated, entry_id, name so this should map to a class or a Dictionary like somebody already suggested in the comments.

Else it should look something like this in JSON:

"elements": ["string1", "string2", "string3"]

Upvotes: 1

mehdi farhadi
mehdi farhadi

Reputation: 1532

you must use List or IEnumerable of string insted Maintenance like this code:

var ticket_data = JsonConvert.DeserializeObject<List<string>>(source);

then set your element of Maintenance class like this code

    Elements =ticket_data ;

Upvotes: 0

Related Questions