Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 反序列化具有未知属性的对象_Json_Serialization_Dictionary - Fatal编程技术网

Json 反序列化具有未知属性的对象

Json 反序列化具有未知属性的对象,json,serialization,dictionary,Json,Serialization,Dictionary,我有以下JSON字符串: { "id": "0", "version": "1.1", "result": { "status": "{\"1\": \"CONTINUOUS\", \"3\": \"NOT_CONFIGURED\", \"2\": \"NOT_CONFIGURED\", \"4\": \"EVENTO\"}" } } 我想将这个字符串反序列化为c类。首先,我使用了json2csharp.com,我使用这些c类来反序列化字

我有以下JSON字符串:

    {
    "id": "0",
    "version": "1.1",
    "result": {
        "status": "{\"1\": \"CONTINUOUS\", \"3\": \"NOT_CONFIGURED\", \"2\": \"NOT_CONFIGURED\", \"4\": \"EVENTO\"}"
    }
}
我想将这个字符串反序列化为c类。首先,我使用了json2csharp.com,我使用这些c类来反序列化字符串:

public class Result {
    public string status { get; set; }
}

public class RootObject {
    public string id { get; set; }
    public string version { get; set; }
    public Result result { get; set; }
}
"status": "{\"1\": \"CONTINUOUS\", \"3\": \"NOT_CONFIGURED\", \"2\": \"NOT_CONFIGURED\", \"4\": \"EVENTO\"}"
此解决方案对我无效,因为状态不是字符串,而是字典对象。这本字典的键和值不是固定的,可能会有所不同

我的解决方法:

我在结果类中添加了一个方法来获取该字典,但我意识到这种解决方法不是很漂亮,我相信有人可以为我找到更好的解决方案。 使用以下方法初始化:

public class Result {
     public string status { get; set; }
     public Dictionary < string, string > GetValues() {
         return JsonConvert.DeserializeObject < Dictionary < string, string >> (status);
     }
 }

提前感谢

这里的问题是:

如何从字符串中获取词典:

public class Result {
    public string status { get; set; }
}

public class RootObject {
    public string id { get; set; }
    public string version { get; set; }
    public Result result { get; set; }
}
"status": "{\"1\": \"CONTINUOUS\", \"3\": \"NOT_CONFIGURED\", \"2\": \"NOT_CONFIGURED\", \"4\": \"EVENTO\"}"
您知道,状态键指向string类型的值,并且该字符串的格式为dictionary。您还知道字典是{key:values-pairs-sequence-}

剩下的唯一问题是键和值的类型。如果您的键和值总是相同的类型,比如说,整数和字符串,那么问题就解决了


只需将状态字符串解析到字典中。

我忘了说我已经在结果类中包含了GetValues方法,因为如果我将status属性作为dictionary,则无法工作

JsonSerializationException 将值{1:连续,3:未配置,2:未配置,4:未配置}转换为类型“System.Collections.Generic.Dictionary2[System.String,System.String]”时出错。路径“结果状态”,第1行,位置157。
+InnerException{无法从System.String强制转换或转换为System.Collections.Generic.Dictionary2[System.String,System.String].}System.Exception{System.ArgumentException}

这看起来不像是有效的JSON,更像是嵌套JSON或类似的东西。你不能像你已经承认的那样一次性反序列化。您是否能够修复JSON字符串,从而不需要在C中处理它?