Json反序列化对象

时间:2019-01-27 04:43:47

标签: c# json xamarin

我的模特:

public class RootObject
{
    public double Balance { get; set; }
    public string CardCode { get; set; }
    public string CardName { get; set; }
    public string PriceLevel { get; set; }
    public bool Status { get; set; }
}

我的Json回复:

var response = "{\"C0001\":{\"Balance\":3.01,\"CardCode\":\"C0001\",\"CardName\":\"Mubarik\",\"PriceLevel\":\"PL1\",\"Status\":true}}"

如何反序列化以下模型的响应。

2 个答案:

答案 0 :(得分:0)

可能的解决方案之一是:

var result = JsonConvert.DeserializeObject<Dictionary<string, RootObject>>(response);

答案 1 :(得分:-1)

您可以使用Newtonsoft.Json.Linq.JObject来实现,如以下代码所示。

var response = "{\"C0001\":{\"Balance\":3.01,\"CardCode\":\"C0001\",\"CardName\":\"Mubarik\",\"PriceLevel\":\"PL1\",\"Status\":true}}";
JObject search = JObject.Parse(response);
RootObject yourObject = search["C0001"].ToObject<RootObject>();

Online Demo

输出

enter image description here

要了解有关部分JSON片段反序列化的更多信息,可以检查here

编辑:

  

此回应如何? var bp =   “ {\” C0001 \“:{\” Balance \“:3.01,\” CardCode \“:\” C0001 \“,\” CardName \“:\” Mubarik \“,\” PriceLevel \“:\” PL1 \“,\” Status \“:true},\” C0002 \“:{\” Balance \“:1.03,\” CardCode \“:\” C0001 \“,\” CardName \“:\” Richie   Rich \“,\” PriceLevel \“:\” PL2 \“,\”状态\“:true}}” – Mubah Mohamed

根据注释中使用不同ID的JSON获取多个对象的格式,您可以尝试按照以下方式将其转换为RootObject的列表。

 var response = "{\"C0001\":{\"Balance\":3.01,\"CardCode\":\"C0001\",\"CardName\":\"Mubarik\",\"PriceLevel\":\"PL1\",\"Status\":true},\"C0002\":{\"Balance\":1.03,\"CardCode\":\"C0001\",\"CardName\":\"Richie Rich\",\"PriceLevel\":\"PL2\",\"Status\":true}}";
 JObject search = JObject.Parse(response);
 IList<JToken> results = search.Children().ToList();
 List<RootObject> searchResults = new List<RootObject>();
 foreach (JToken result in results)
  {
    RootObject searchResult = result.First.ToObject<RootObject>();
    searchResults.Add(searchResult);
  }

Online Demo