如何在C#中反序列化JSON数据 [英] How do I deserialize JSON data in C#

查看:118
本文介绍了如何在C#中反序列化JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,有人可以提供适当的方法来反序列化此格式的json数据吗:

[{person:{name:"James", age:26}}, {person:{name:"Mary", age:36}}, {person:{name:"Kofi", age:46}}]



我使用的代码如下:

 WebRequest请求= WebRequest.Create(" );
Web响应响应= request.GetResponse();

字符串 json;

使用( var  sr =  StreamReader( response.GetResponseStream()))
{
    json = sr.ReadToEnd();
}


 var  serializer =  JavaScriptSerializer();

 var  persons =序列化程序.反序列化< List< auto>>>(json);

 foreach ( var 项目 in 人)
{
    Console.Write("  + item.name + "  + item.age);
} 



我映射到的类如下:

 公共  class 人
{
  公共 字符串名称{获取; 设置;}
   public   int  age { get ; ;}
} 



当我运行此代码时,我不断获得名称和年龄属性的空值和空字符串.如果有人可以帮助我,我将不胜感激.

解决方案

在发布问题之前,您应该先谷歌搜索

使用C#反序列化JSON [ http://stackoverflow.com/questions/7895105/json-deserialize-c-sharp [ ^ ]

http://procbits.com/2011/04/21/quick-json-serializationdeserialization -in-c/ [ ^ ]

http://www. drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx [



The code i''am using is as below:

WebRequest request = WebRequest.Create("url");
WebResponse response = request.GetResponse();

string json;

using (var sr = new StreamReader(response.GetResponseStream()))
{
    json = sr.ReadToEnd();
}


var serializer = new JavaScriptSerializer();

var persons= serializer.Deserialize<List<auto>>(json);

foreach (var item in persons)
{
    Console.Write("name:" + item.name + " and age: " + item.age);
}



the class I''am mapping to is as below:

public class person
{
  public string name{get;set;}
  public int age{get; set;}
}



I keep getting nulls and empty strings for the name and age properties when I run this code. I will appreciate it a lot if someone can help me out.

解决方案

You should have googled before posting the question

Deserialize JSON with C#[^]

http://stackoverflow.com/questions/7895105/json-deserialize-c-sharp[^]

http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/[^]

http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx[^]


I had to make call item.person.name and item.person.age in the foreach loop and make sure all properties in the person class were of type string.


这篇关于如何在C#中反序列化JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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