Reputation: 213
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;}
}
Upvotes: 0
Views: 2999
Reputation: 154
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;
}
Upvotes: 0
Reputation: 156
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 });
Upvotes: 1