使用动态属性反序列化JSON

时间:2017-04-13 12:13:19

标签: c# json json.net

我必须反序列化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;}
}

2 个答案:

答案 0 :(得分:1)

关于我的评论,也许我们最好写下我的建议的例子:

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

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

答案 1 :(得分:0)

您需要:

使用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;
}