【问题标题】:Access nested key value pairs访问嵌套键值对
【发布时间】:2015-09-30 17:07:50
【问题描述】:

我有一个相对简单的嵌套 JSON 字符串用于下面的数据:

{  "d" : {
     "humidity": "39.21",
     "acc_y": "1.21",
     "ambient_temp": "24.21",
     "air_pressure": "1029.21",
     "object_temp": "23.21",
     "acc_z": "0.21",
     "acc_x": "3.21",
   } 
}

我有一个接收 JSON 字符串和反序列化字符串的 c# windows 服务应用程序。

private static void client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
    {

        //Console.WriteLine(System.Text.Encoding.Default.GetString(e.Message));
        string json = System.Text.Encoding.Default.GetString(e.Message);

        var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(json, new JsonConverter[] { new MyConverter() });

    }

我有一个看起来像这样的 Myconvert 类,它读取 JSON:

class MyConverter : CustomCreationConverter<IDictionary<string, object>>
{
    public override IDictionary<string, object> Create(Type objectType)
    {
        return new Dictionary<string, object>();
    }

    public override bool CanConvert(Type objectType)
    {
        // in addition to handling IDictionary<string, object>
        // we want to handle the deserialization of dict value
        // which is of type object
        return objectType == typeof(object) || base.CanConvert(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartObject
            || reader.TokenType == JsonToken.Null)
            return base.ReadJson(reader, objectType, existingValue, serializer);

        // if the next token is not an object
        // then fall back on standard deserializer (strings, numbers etc.)
        return serializer.Deserialize(reader);
    }
}

我可以在 obj 对象的调试窗口中看到 JSON 数据。

这可能是一个非常直接的问题,我如何提取 JSON 键值对数据(例如湿度、环境温度)以在我的程序中使用,因为目前我只能在调试窗口中看到它们?

感谢您的帮助!

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    您实际上不需要转换器来反序列化此 JSON。一个简单的包装类就可以做到:

    class Wrapper
    {
        public Dictionary<string, object> d { get; set; }
    }
    

    然后:

    Dictionary<string, object> obj = JsonConvert.DeserializeObject<Wrapper>(json).d;
    

    小提琴:https://dotnetfiddle.net/vnoQxi

    【讨论】:

    • 非常好.. 谢谢你的回复。不错的简单解决方案!
    • 没问题。很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多