简体   繁体   English

如何反序列化具有数组的对象的json? 使用Newtonsoft xamarin

[英]How Can I deserialize a json that is an object with an array? using Newtonsoft xamarin

I am using Xamarin forms and Newtonsoft to deserialize 我正在使用Xamarin表格和Newtonsoft进行反序列化

It doesn't work: 它不起作用:

var itens = JsonConvert.DeserializeObject<List<Model.Loja>>(json);

Here is my JSON: 这是我的JSON:

{
  "one": {
    "two": [
      {
        "cod": 142,
        "nome": "name",
        "phone": "23423",
        "endereco": "address",
        "cidade": "city"
      },
      {
        "cod": 142,
        "nome": "name",
        "phone": "23423",
        "endereco": "address",
        "cidade": "city"
      }
    ]
  }
}

Your model needs to match your JSON structure. 您的模型需要匹配JSON结构。 Try using these classes: 尝试使用以下类:

public class RootObject
{
    public One one { get; set; }
}

public class One
{
    public List<Loja> two { get; set; }
}

public class Loja
{
    public int cod { get; set; }
    public string nome { get; set; }
    public string phone { get; set; }
    public string endereco { get; set; }
    public string cidade { get; set; }
}

Then deserialize like this: 然后像这样反序列化:

List<Loja> items = JsonConvert.DeserializeObject<RootObject>(json).one.two;

You can make a specific model class for that json, try to use http://json2csharp.com/ , 您可以为该json创建一个特定的模型类,尝试使用http://json2csharp.com/

and then you can parse it using newtonsoft. 然后您可以使用newtonsoft对其进行解析。

If you are using json2chsarp then your specific class will called RootObject, but you can rename it to match your model. 如果您使用的是json2chsarp,则您的特定类将称为RootObject,但是您可以重命名它以匹配您的模型。

var obj = JsonConvert.DeserializeObject<YourSpecificClass>(json);

The problem was the "[ ]". 问题是“ []”。 I used 我用了

response = json.Substring(json.IndexOf('['));
response = json.Substring(0, json.LastIndexOf(']') + 1);

And solved it. 并解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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