序列化反序列化匿名孩子JSON性能建模 [英] Serialize deserialize anonymous child JSON properties to model

查看:153
本文介绍了序列化反序列化匿名孩子JSON性能建模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我从接收数据的API。那API是在我的掌握它是如何构成的,我需要序列化和反序列化JSON输出到数据映射到我的模型。



一切都工作得很好JSON是很好的格式化命名属性在哪里。



你可以做什么在没有命名值并没有仅仅整数和字符串数组?像在地点



这里是JSON的示例:

  {ID:2160336,activation_date:2013年8月1日,到期日期:2013年8月29日,称号:业务经理,地点:{103:剑桥,107:伦敦}} 

我有一个像模型:

 公共类ItemResults 
{
公众诠释标识{搞定;组; }

公众的DateTime Activation_Date {搞定;组; }

公众的DateTime EXPIRATION_DATE {搞定;组; }

公共字符串名称{搞定;组; }

公共场所位置{搞定;组; }
}

公共类位置
{
公众诠释标识{搞定;组; }

公共字符串值{获得;组; }
}

和我使用的是内置的ajax序列化映射:

 保护牛逼MapRawApiResponseTo< T>(串响应)
{
如果(string.IsNullOrEmpty(响应))
{
返回默认值(T);
}

无功序列化=新的JavaScriptSerializer();

返回serialize.Deserialize< T>(响应);
}

VAR的结果= MapRawApiResponseTo< ItemResults>(rawApiResponse);



所以ID和所有其他属性都捡起并映射但每次我这样做,我似乎无法到位置映射。



非常感谢


解决方案

 公众解释< INT,串>位置{搞定;组; } 



完成任务;你会发现,使用Json.NET,至少,即

  VAR的结果= JsonConvert.DeserializeObject< ItemResults>(JSON); 



你在 result.Locations 2项;特别是结果[103] =剑桥; 结果[107] =伦敦;


I have an API I am receiving data from. That API is out of my control on how it is structured, and I need to serialize and deserialize the JSON output to map the data to my model.

Everything works well where JSON is nicely formatted with named properties.

What can you do where there is no named value and there is just an array of ints and strings? like under locations

here is a sample of the JSON:

{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}

I have models that are like:

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

and I am mapping using the inbuilt ajax serialization:

 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);

So the ID and all other properties are picked up and mapped but what every I do I can not seem to map the locations.

Many thanks

解决方案

public Dictionary<int,string> Locations { get; set; }

job done; you should find that using Json.NET, at least, i.e.

var result = JsonConvert.DeserializeObject<ItemResults>(json);

you get 2 entries in result.Locations; specifically result[103] = "Cambridge"; and result[107] = "London";

这篇关于序列化反序列化匿名孩子JSON性能建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆