简体   繁体   中英

Can not deserialize json to Dictionary<string, List<Purchase>>

I can not deserialize json to Dictionary<string, List<Purchas>> in C#.

Here is my .json :

{
  "Ukraine": {
    {
      "Credits": 500,
      "Name": "Clever goat",
      "Price": {
        "Amount": 100,
        "Currency": "UAH"
      }
    },
    {
      "Credits": 1000,
      "Name": "Smart hare",
      "Price": {
        "Amount": 190,
        "Currency": "UAH"
      }
    }
  },

  "USA": {
    {
      "Credits": 500,
      "Name": "Clever goat",
      "Price": {
        "Amount": 10,
        "Currency": "USD"
      }
    },
    {
      "Credits": 1000,
      "Name": "Smart hare",
      "Price": {
        "Amount": 19,
        "Currency": "USD"
      }
    }
  }
}

Here is my Purchase class:

public class Price
{
    public int Amount { get; set; }
    public string Currency { get; set; }
}

public class Purchase
{
    public int Credits { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

Here is how I am trying to deserialize it:

var countryToPurchases = JsonConvert.DeserializeObject<Dictionary<string, List<Purchase>>>(dataJSON);

Here is the error I am getting:

JsonReaderException: Invalid property identifier character: {. Path 'Ukraine', line 3, position 4. Newtonsoft.Json.JsonTextReader.ParseProperty()

What am I missing here?

You have two problems here:

  1. The Json is invalid. There should be arrays there but there aren't.
    A valid json would look like this:
[
  {
    "Ukraine": [
      {
        "Credits": 500,
        "Name": "Clever goat",
        "Price": {
          "Amount": 100,
          "Currency": "UAH"
        }
      },
      {
        "Credits": 1000,
        "Name": "Smart hare",
        "Price": {
          "Amount": 190,
          "Currency": "UAH"
        }
      }
    ]
  },
  {
    "USA": [
      {
        "Credits": 500,
        "Name": "Clever goat",
        "Price": {
          "Amount": 10,
          "Currency": "USD"
        }
      },
      {
        "Credits": 1000,
        "Name": "Smart hare",
        "Price": {
          "Amount": 19,
          "Currency": "USD"
        }
      }
    ]
  }
]
  1. The Price property should be of type Price , not int .
public class Purchase
{
    public int Credits { get; set; }
    public string Name { get; set; }
    public Price Price { get; set; }
}

please check this json and see if it's works :

 {
 "Ukraine": {
  "Credits": 500,
  "Name": "Clever goat",
  "Price": {
   "Amount": 100,
   "Currency": "UAH"
 }
},
 "USA": {
  "Credits": 500,
  "Name": "Clever goat",
  "Price": {
    "Amount": 10,
    "Currency": "USD"
  }
 }
}

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