我得到了这个回复。如何去除JSON?
[{
"NoOfRecord":"2",
"data":[
{
"name": "Pinky",
"Id": "8989898",
"PhoneNumber": "918934",
"status": "Success",
},
{
"name": "Kajol",
"Id": "2345678",
"PhoneNumber": "915566",
"status": "Fail",
}
]
}]
我试过这样,但收到错误。
我为此创建了2个类。
public class JsonResult2
{
public string NoOfRecord{ get; set; }
public JsonData Data { get; set; }
}
public class JsonData
{
public string name{ get; set; }
public string Id{ get; set; }
public string PhoneNumber{ get; set; }
public string status{ get; set; }
}
当我这样写作时,会收到错误。
var JsonData = JsonConvert.DeserializeObject<JsonResult2>(ResponseJson);
我正在使用Newtonsoft的库(使用Newtonsoft.Json;)
如何访问所有name
,id
,phonenumber
和status
。
我将获得的响应存储在名为ResponseJson
的字符串中。
错误:无法将JSON数组反序列化为类型&#39; JsonResult2&#39;
答案 0 :(得分:1)
First of all, your JSON string is invalid. It has two commas as shown below which shouldn't be there:
[{
"NoOfRecord":"2",
"data":[
{
"name": "Pinky",
"Id": "8989898",
"PhoneNumber": "918934",
"status": "Success", <-- This comma shouldn't be there
},
{
"name": "Kajol",
"Id": "2345678",
"PhoneNumber": "915566",
"status": "Fail", <-- This comma shouldn't be there
}
]
}]
Once those commas are removed, your JSON is valid. Here's how it would look:
[{
"NoOfRecord":"2",
"data":[
{
"name": "Pinky",
"Id": "8989898",
"PhoneNumber": "918934",
"status": "Success"
},
{
"name": "Kajol",
"Id": "2345678",
"PhoneNumber": "915566",
"status": "Fail"
}
]
}]
Now the outermost brackets []
mean that you are receiving an array, not object. So your de-serialization syntax should be:
var JsonData = JsonConvert.DeserializeObject<List<JsonResult2>>(ResponseJson);
Then you need to ensure that the properties in the JSON match those of your entities. Also note the two []
square brackets against data
in the JSON. That means you are expecting an array, not object. That means Data
should be List<JsonData>
instead of JsonData
. So you'd need to update JsonResult2
as follows:
public class JsonResult2
{
public string NoOfRecord { get; set; }
public List<JsonData> Data { get; set; }
}
Also, if you are certain that NoOfRecord
is a number, you might want to change the type of NoOfRecord within JsonResult2
to int
.