访问嵌套的键值对

时间:2015-09-30 17:07:50

标签: c# json json.net

我有一个相对简单的嵌套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",
   } 
}

我有一个c#windows服务应用程序,它接收JSON字符串和Deserialize字符串。

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键值对数据(例如,湿度,环境温度),因为目前我只能在调试窗口中看到它们?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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

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

然后:

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

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