将json字符串转换为类 [英] Convert json string to class

查看:127
本文介绍了将json字符串转换为类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hai我有这样的json字符串







[{StudentId:3 RollNo: 1},{ StudentId: 2, RollNo: 2},{ StudentId: 1, RollNo: 3},{ StudentId :4,RollNo:4}]



  public   class 详细信息
{
public string StudentId { get ; set ; }
public string RollNo { get ; set ; }
}





详情result = JsonConvert.DeserializeObject< details>(str); 





但错误显示如下



无法反序列化当前的JSON数组(例如[ 1  2  3 ]) into  type '  AdmissionService + Details'因为类型需要JSON  object (例如{  name  value})反序列化正确。 
要修复错误,请将JSON更改为JSON object (例如{ name value})或将反序列化类型更改为数组或实现集合的类型 interface (例如ICollection,IList),如List< ; T>可以从 JSON数组中反序列化。 JsonArrayAttribute也可以添加到类型中,以强制它从 JSON数组反序列化
Path ' ',line 1 ,position 1





任何人都可以帮忙??? div class =h2_lin>解决方案

请尝试如下。



列表<详情> data = JsonConvert.DeserializeObject< List< Details>>(jsonString); 





注意:我希望你正在使用json.NET。


试试这个

 JavaScriptSerializer jsonSerializer =  JavaScriptSerializer(); 
详细信息objDetails = jsonSerializer.Deserialize< details>(jsonInput)
< / details >


Hai I have json string like this



[{"StudentId":"3","RollNo":"1"},{"StudentId":"2","RollNo":"2"},{"StudentId":"1","RollNo":"3"},{"StudentId":"4","RollNo":"4"}]

public class Details
   {
       public string StudentId { get; set; }
       public string RollNo { get; set; }
   }



Details result = JsonConvert.DeserializeObject<details>(str);



but error showing like this

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AdmissionService+Details' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.



Can anyone help???

解决方案

Please try is as below.

List<Details> data = JsonConvert.DeserializeObject<List<Details>>(jsonString);



NOTE: I hope you're using json.NET.


Try this

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Details objDetails  = jsonSerializer.Deserialize<details>(jsonInput)
</details>


这篇关于将json字符串转换为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆