简体   繁体   中英

Newtonsoft.Json Deserialize issue

Trying to deserialize json from a web api. Here is the incoming json:

{"0":{"productname":"France and the French",
"imageurl":"http://img.rakuten.com/PIC/32994457/0/1/250/32994457.jpg",
"producturl":"http://www.theurl.com/rd.aspx?3d",
"price":"19.51",
"currency":"USD",
"saleprice":"",
"storename":"Buy.com (dba Rakuten.com Shopping)"}
}

Here is my data class:

public class Product
{
    [JsonProperty("productname")]
    public string productname { get; set; }

    [JsonProperty("imageurl")]
    public string imageurl { get; set; }

    [JsonProperty("producturl")]
    public string producturl { get; set; }

    [JsonProperty("price")]
    public string price { get; set; }

    [JsonProperty("currency")]
    public string currency { get; set; }

    [JsonProperty("saleprice")]
    public string saleprice { get; set; }

    [JsonProperty("storename")]
    public string storename { get; set; }
}

And here is the code:

string json = upcclient.GetProductJSON(upc, accessToken);
Product myproduct = JsonConvert.DeserializeObject<Product>(json);

Should be pretty straight forward. json is getting populated, but no matter what I try - Product as an list of products in a master data class, array of product, etc, myproduct is never populated.

Thanks for the help in advance. This stuff isn't usually this hard. I've done it 50 times or so, but this time is getting to me.

In the example JSON you posted, Product is an object contained within the 0 field of a root object, and the root object doesn't appear to be using JSON array syntax. Unfortunately, this is fairly ugly to elegantly map to a C# class if you expect to get an arbitrary number of results. If you know you're only going to get one product, you can simply add a root class:

public class ProductWrapper
{
  [JsonProperty("0")]
  public Product Product
  {
    get;
    set;
  }
}

and do:

string json = upcclient.GetProductJSON(upc, accessToken);
Product myproduct = JsonConvert.DeserializeObject<ProductWrapper>(json).Product;

I suspect this API is designed to potentially return multiple products, though, so this may not be what you're looking for. If this is an API you have control over, it may be worth requesting that the JSON actually returns an array of products, rather than the object that it returns now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM