c# - 序列化反序列化匿名子 JSON 属性以建模

标签 c# serialization deserialization

我有一个从中接收数据的 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 和所有其他属性都被拾取并映射,但我所做的一切似乎都无法映射位置。

非常感谢

最佳答案

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

工作完成;你应该发现使用 Json.NET,至少,即

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

您在 result.Locations 中得到 2 个条目;特别是 result[103] = "Cambridge";result[107] = "London";

关于c# - 序列化反序列化匿名子 JSON 属性以建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233005/

相关文章:

c# - 使用 XmlMessageFormater 序列化的消息拒绝反序列化 List<T> 成员

powershell - 反序列化对象类型问题 - 特别是 Powershell 5 类和 Import-CliXml

c# - WinForm 与 WPF .Close() 事件

c# - SQL Express 连接字符串 : mdf file location relative to application location

c# - 使用无效枚举值序列化对象

c# - 嵌套自身的类的 Protobuf-net 序列化

c# - 基于用户角色的 ASP.NET WebAPI 条件序列化

Java序列化

c# - 我想安装Ubuntu或除Microsoft Windows以外的任何其他操作系统,请告诉我哪个操作系统最适合开发

c# - 匿名 lambda ?