我有一个API,我正在接收数据。该API不受我对其结构的控制,我需要序列化和反序列化JSON输出以将数据映射到我的模型。
在使用命名属性很好地格式化JSON的地方,一切都很好。
如果没有命名值,只有一个整数和字符串数组,你能做什么?比如位置
这是JSON的一个示例:
{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}
我的模型类似于:
public class ItemResults
{
public int Id { get; set; }
public DateTime Activation_Date { get; set; }
public DateTime Expiration_Date{ get; set; }
public string Title { get; set; }
public Location Locations { get; set; }
}
public class Location
{
public int Id { get; set; }
public string value { get; set; }
}
我正在使用内置的ajax序列化进行映射:
protected T MapRawApiResponseTo<T>( string response )
{
if ( string.IsNullOrEmpty( response ) )
{
return default( T );
}
var serialize = new JavaScriptSerializer();
return serialize.Deserialize<T>( response );
}
var results = MapRawApiResponseTo<ItemResults>(rawApiResponse);
因此,ID和所有其他属性都会被拾取并映射,但我所做的每件事都无法映射到位置。
非常感谢
答案 0 :(得分:2)
public Dictionary<int,string> Locations { get; set; }
完成工作;你应该发现使用Json.NET,至少,即
var result = JsonConvert.DeserializeObject<ItemResults>(json);
您在result.Locations
中获得2个条目;具体为result[103] = "Cambridge";
和result[107] = "London";
答案 1 :(得分:2)
如果您不介意,可以使用字典解决方法:
class Program
{
static void Main(string[] args)
{
string json =
"{'id':'2160336','activation_date':'2013-08-01','expiration_date':'2013-08-29','title':'Practice Manager','locations':{'103':'Cambridge','107':'London'}}";
var deserializeObject = JsonConvert.DeserializeObject<ItemResults>(json);
Console.WriteLine("{0}:{1}", deserializeObject.Locations.First().Key, deserializeObject.Locations.First().Value);
Console.ReadKey();
}
}
public class ItemResults
{
public int Id { get; set; }
public DateTime Activation_Date { get; set; }
public DateTime Expiration_Date { get; set; }
public string Title { get; set; }
public Dictionary<int, string> Locations { get; set; }
}
您也可以使用手动解析,例如:Json.NET (Newtonsoft.Json) - Two 'properties' with same name?
答案 2 :(得分:1)
这将有效:
public Dictionary<string, string> Locations { get; set; }
public IEnumerable<Location> LocationObjects { get { return Locations
.Select(x => new Location { Id = int.Parse(x.Key), value = x.Value }); } }
答案 3 :(得分:1)
我建议您使用以下解决方案:
public class ItemResults
{
public int Id { get; set; }
public DateTime Activation_Date { get; set; }
public DateTime Expiration_Date { get; set; }
public string Title { get; set; }
[JsonProperty("locations")]
public JObject JsonLocations { get; set; }
[JsonIgnore]
public List<Location> Locations { get; set; }
[OnDeserialized]
public void OnDeserializedMethod(StreamingContext context)
{
this.Locations = new List<Location>();
foreach (KeyValuePair<string, JToken> item in this.JsonLocations)
{
this.Locations.Add(new Location() { Id = int.Parse(item.Key), value = item.Value.ToString() });
}
}
}
public class Location
{
public int Id { get; set; }
public string value { get; set; }
}
在您必须使用:JsonConvert.DeserializeObject<ItemResults>(json);