简体   繁体   中英

Deserializing JSON with dynamic property

I have to deserialize a JSON response(from a wep API) . The problem is that this API returns JSON with dynamic property. Had it been like

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

it would have been perfect but the response is string and is returned like:

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

Where the first property is "EmployeeCode" and the second property is "CityId". How can I use JSON.Net to serialize it into the following class?

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

Regarding my comment maybe it us better to write the example of what I ment:

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

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

You'll need:

using System.IO;

using System.Text;

using 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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