despoof
despoof

Reputation: 3

How to deserialize this json-data?

I have JSON-data. I using Newtonsoft.Json for deserialize

{
    {
        "id":"951357",
        "name":"Test Name",
        "hometown":
        {
            "id":"12345",
            "name":"city"
        },

        "bff": [
            {
                "people": {
                    "id":"123789",
                    "name":"People Name"
                },              

                "id":"147369"
            }
        ],

    }
}

I create classes:

 public class Data
{
    [JsonProperty("id")]
    public string Id;

    [JsonProperty("name")]
    public string Name;

    [JsonProperty("hometown")]
    public string[] Hometown;

    [JsonProperty("bff")]
    public Bff[] Bff;
}

public class Bff
{
    [JsonProperty("people")]
    public People[] People;

    [JsonProperty("id")]
    public string Id;
}

public class People
{
    [JsonProperty("id")]
    public string Id;

    [JsonProperty("name")]
    public string Namel
}

public class Hometown
{
    [JsonProperty("id")]
    public int Id;

    [JsonProperty("name")]
    public string Name;
}

But if I call Data datatest = JsonConvert.DeserializeObject<Data>(data); where "data" it's json array i have this error:

The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string)' has some invalid arguments

Please let me know if you need more info.

Upvotes: 0

Views: 68

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

The problem is here:

"hometown":
{
    "id":"12345",
    "name":"city"
},

you are passing a single object while your mapping class is expecting an array:

[JsonProperty("hometown")]
public string[] Hometown;

Do:

"hometown":
[{
    "id":"12345",
    "name":"city"
}],

In addition:

  1. Same problem of not passing it as an array [] for People
  2. Having your Hometown property of type string[] instead of Hometowm[]
  3. You have a {} set to much around your json

This is the valid JSON:

{
    "id":"951357",
    "name":"Test Name",
    "hometown": [{
        "id":"12345",
        "name":"city"
        }],

    "bff": [{
        "people": [{
            "id":"123789",
            "name":"People Name"
        }],
        "id":"147369"
    }],
}

And Valid code:

public class Data
{
    [JsonProperty("id")]
    public string Id;
    [JsonProperty("name")]
    public string Name;
    [JsonProperty("hometown")]
    public Hometown[] Hometown;
    [JsonProperty("bff")]
    public Bff[] Bff;
}

public class Bff
{
    [JsonProperty("people")]
    public People[] People;
    [JsonProperty("id")]
    public string Id;
}

public class People
{
    [JsonProperty("id")]
    public string Id;
    [JsonProperty("name")]
    public string Name;
}

public class Hometown
{
    [JsonProperty("id")]
    public int Id;
    [JsonProperty("name")]
    public string Name;
}

Upvotes: 2

Related Questions