C#JSONConverter自定义序列化

时间:2017-11-08 20:57:03

标签: c# json

我从某个API接收JSON具有动态属性。

我采用了自定义的JsonConverter方法。有没有更简单的方法来解决这个问题?

这是JSON返回

{
    "kind": "tm:ltm:pool:poolstats",
    "generation": 1,
    "selfLink": "https://localhost/mgmt/tm/ltm/pool/test-mypoolname_https_main/stats?ver=12.1.2",
    "entries": {
        "https://localhost/mgmt/tm/ltm/pool/test-mypoolname_https_main/~Common~test-mypoolname_https_main/stats": {
            "nestedStats": {
                "kind": "tm:ltm:pool:poolstats",
                "selfLink": "https://localhost/mgmt/tm/ltm/pool/test-mypoolname_https_main/~Common~test-mypoolname_https_main/stats?ver=12.1.2"
            }
        }
    }
}

"entries": { "https://..." }是始终发生变化的部分,具体取决于我从API请求的内容。

以下是保存此信息的类结构:

public partial class PoolStatistics
{
    [JsonProperty("entries")]
    public EntriesWrapper Entries { get; set; }

    [JsonProperty("generation")]
    public long Generation { get; set; }

    [JsonProperty("kind")]
    public string Kind { get; set; }

    [JsonProperty("selfLink")]
    public string SelfLink { get; set; }


    [JsonConverter(typeof(PoolEntriesConverter))]
    public partial class EntriesWrapper
    {
        public string Name { get; set; }

        [JsonProperty("nestedStats")]
        public NestedStats NestedStats { get; set; }
    }

    public partial class NestedStats
    {
        [JsonProperty("kind")]
        public string Kind { get; set; }

        [JsonProperty("selfLink")]
        public string SelfLink { get; set; }
    }
}

通过PoolEntriesConverter上的以下内容覆盖反序列化:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    JObject jo = JObject.Load(reader);
    NestedStats nestedStats = (jo.First.First[NESTED_STATS]).ToObject<NestedStats>();

    EntriesWrapper entries = new EntriesWrapper
    {
        NestedStats = nestedStats,
        Name = jo.First.Path
    };

    return entries;
}

Overriden WriteJson(序列化) - 抛出异常:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    EntriesWrapper entries = (EntriesWrapper)value;

    JObject jo = new JObject(
        new JProperty(NESTED_STATS, entries.NestedStats),
        new JProperty(entries.Name, entries.Name));
}

错误说明:

  

System.ArgumentException:'无法确定JSON对象类型   键入F5IntegrationLib.Models.Pools.PoolStatistics + NestedStats。'

1 个答案:

答案 0 :(得分:1)

如果您声明类似

的模式
public class NestedStats
{
    public string kind { get; set; }
    public string selfLink { get; set; }
}

public class Entry
{
    public NestedStats NestedStats { get; set; }
}

public class Root
{
    public string kind { get; set; }
    public int generation { get; set; }
    public string selfLink { get; set; }
    public Dictionary<string, Entry> entries { get; set; }
}

然后你可以反序列化为

var obj = JsonConvert.DeserializeObject<Root>(json);