繁体   English   中英

使用动态属性反序列化JSON

[英]Deserializing JSON with dynamic property

我必须反序列化JSON响应(来自wep API)。 问题在于此API返回具有动态属性的JSON。 曾经有过

{
"employees":
[{
"employeeCode": "ABC",
"cityId": 123
},{
"employeeCode": "DEF",
"cityId": 234
}]
}

本来是完美的,但是响应是字符串,并且返回如下:

var response = @"{"ABC": 123, "DEF": 234}";

其中第一个属性是“ EmployeeCode”,第二个属性是“ CityId”。 如何使用JSON.Net将其序列化为以下类?

public class Employees
{
public string employeeCode {get; set;}
public string cityId {get; set;}
}

关于我的评论,也许我们最好写一个我所评论的例子:

string json = @"{""ABC"": 123, ""DEF"": 234}";

var employees = JsonConvert.DeserializeObject<Dictionary<string, int>>(json).Select(x => new Employees() { employeeCode = x.Key, cityId  = x.Value });

你需要:

使用System.IO;

使用System.Text;

使用System.Runtime.Serialization.Json;

public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}

public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM