有没有简单的方法在c#
中解析JSOn{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}
以及多重结果。
答案 0 :(得分:56)
请按照以下步骤操作:
Newtonsoft.Json
库添加到项目中; 使用以下代码转换从您的服务收到的JSON:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
(随意将RootObject
重命名为对您更有意义的内容。其他类应保持不变。)
答案 1 :(得分:20)
您可以安全地使用内置JavaScriptSerializer
而无需引用其他第三方库:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);
答案 2 :(得分:4)
我找到了一种不使用任何外部API的方法来获取它
using (var w = new WebClient())
{
var json_data = string.Empty;
string url = "YOUR URL";
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var result = jsSerializer.DeserializeObject(json_data);
Dictionary<string, object> obj2 = new Dictionary<string, object>();
obj2=(Dictionary<string,object>)(result);
string val=obj2["KEYNAME"].ToString();
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
}
答案 3 :(得分:1)
对我来说......最简单的方法是使用JSON.net对表示对象的实体进行反序列化,例如:
public class Message
{
public string status { get; set; }
public string messageid { get; set; }
public string gsm { get; set; }
}
public class YourRootEntity
{
public string type { get; set; }
public string totalprice { get; set; }
public string totalgsm { get; set; }
public string remaincredit { get; set; }
public List<Message> messages { get; set; }
}
这样做:
YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);