本文介绍了将JSON转换为对象失败-无法将当前JSON对象反序列化为System.Collections.Generic.List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用www.textlocal.in的API,该API返回JSON格式的对象.

I'm using the API of www.textlocal.in, which returns a JSON formatted object.

JSON

{  
   "warnings":[  
      {  
         "message":"Number is in DND",
         "numbers":"917000000000"
      }
   ],
   "balance":900,
   "batch_id":311110011,
   "cost":1,
   "num_messages":1,
   "message":{  
      "num_parts":1,
      "sender":"TXTLCL",
      "content":"Test1"
   },
   "receipt_url":"",
   "custom":"",
   "inDND":[  
      "917000000000"
   ],
   "messages":[  
      {  
         "id":"1350123781",
         "recipient":918819437284
      }
   ],
   "status":"success"
}

我要用来解析JSON的代码:

private void button1_Click(object sender, EventArgs e)
{
    var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
}

public class jsonToObj
{
    public warnings[] warnings { get; set; }

    public int balance { get; set; }
    public int batch_id { get; set; }
    public int cost { get; set; }
    public int num_messages { get; set; }
    public message message { get; set; }
    public string receipt_url { get; set; }
    public string custom { get; set; }
    public messages[] messages { get; set; }
    public string status { get; set; }
}


public class warnings
{
    public string message { get; set; }
    public string numbers { get; set; }
}

public class messages
{
    public string id { get; set; }
    public int recipient { get; set; }
}

public class message
{
    public int num_part { get; set; }
    public string sender { get; set; }
    public string content { get; set; }
}

我收到以下消息的异常消息:

推荐答案

首先,您必须弄清楚API返回的内容.

First of all you have to figure out what your API returns.

现在,您正在尝试解析jsonToObj Arrays(List<jsonToObj[]>)的List.您必须决定使用API​​现在提供的jsonToObj[]List<jsonToObj>还是简单的jsonToObj:

Right now you're trying to parse a List of jsonToObj Arrays (List<jsonToObj[]>). You have to decide whether to use a jsonToObj[] or List<jsonToObj> or a simple jsonToObj which your API provides now:

var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);

但是这会引发:

因此请确保为此使用Long.

public class messages
{
    public string id { get; set; }
    public long recipient { get; set; }
}

此外,如果需要以下信息,您可以inDND添加到您的jsonToObj类中:

Furthermore you can add inDND to your jsonToObj class if you need the info:

public class jsonToObj
{
  ...
  public string[] inDND { get; set; }
  ...
}

这篇关于将JSON转换为对象失败-无法将当前JSON对象反序列化为System.Collections.Generic.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:56