[英]Dynamic JObject - parse invalid JSON
Consider I have following json: 考虑一下我跟随json:
{ "version": "1.0" }
I can parse it to dynamic JObject and use: 我可以将它解析为动态JObject并使用:
dynamic result = JObject.Parse(myJson);
string verison = result.Version; //works <3
But server returns the following json 但是服务器返回以下json
{ { "version": "1.0" } }
This json is consider as valid by newtonsoft, but cannot access version anymore: 这个json被newtonsoft视为有效,但不能再访问版本了:
dynamic result = JObject.Parse(myJson);
string verison = result.Version; //error
How to access Version
when onlt dynamic result
is avalable? 当onlt动态result
可用时,如何访问Version
?
{ { "version": "1.0" } }
This json is consider as valid by newtonsoft{ { "version": "1.0" } }
这个json被newtonsoft视为有效
That is incorrect, you will not be able to parse this and will receive a exception of type Newtonsoft.Json.JsonReaderException
(with: Invalid property identifier character: {. Path '', line 1, position 2.) 这是不正确的,你将无法解析它并将收到类型Newtonsoft.Json.JsonReaderException
的异常(带:无效的属性标识符字符:{。路径'',第1行,位置2)
Invalid JSON: 无效的JSON:
{ { "version": "1.0" } }
Valid JSON: 有效的JSON:
{ "version": "1.0" }
(In case you have server control, I suggest you make the necessary steps on the server to return valid JSON) (如果您有服务器控件,我建议您在服务器上执行必要的步骤以返回有效的JSON)
However, worst case scenario, you could make this invalid JSON valid by removing the first char {
and last char }
before parsing it. 但是,在最糟糕的情况下,您可以通过在解析之前删除第一个char {
和last char }
来使此无效JSON有效。 For example like so: 例如:
var myJson = json.Substring(1, json.Length - 2);
dynamic result = JObject.Parse(myJson);
string version = result.version;
Where json
here was the original response containing the invalid JSON. 这里的json
是包含无效JSON的原始响应。
Also note that for the JSON you provided you must use lowercase version
as result.version
. 另请注意,对于您提供的JSON,您必须使用小写version
作为result.version
。 The dynamic property name must match exactly the one in the JSON 动态属性名称必须与JSON中的名称完全匹配
I think you trouble in capital "V" in "Version". 我认为你在“版本”中的资本“V”中遇到麻烦。 Should be "result.version" 应该是“result.version”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.