C#解析可能具有简单类型的json [英] C# Parsing json that may have simple types
问题描述
从C#中,我正在调用返回JSON的RESTful Web服务.该服务可以返回任意Javascript对象,我们在编译时不知道其结构.
From C# I'm calling RESTful web service that returns JSON. The service can return an arbitrary Javascript object, we don't know its structure at compile time.
通常,它返回一个JSON对象,但是在某些情况下,它返回一个简单的字符串.当我尝试反序列化简单字符串时,JSON.Net引发运行时错误.
Usually, it returns a JSON object, but there are situations where it returns a simple string. JSON.Net throws a runtime error when I try to deserialize the simple string.
dynamic dyn = JsonConvert.DeserializeObject("just a string");
抛出:
Newtonsoft.Json.JsonReaderException was unhandled by user code
HResult=-2146233088
Message=Unexpected character encountered while parsing value: j. Path '', line 0, position 0.
我阅读了以下答案 这个简单的字符串是否被视为有效的JSON?,共识似乎是返回一个简单的字符串作为JSON是合法的,但是许多实现尚不支持此功能.
I read the answers to Is this simple string considered valid JSON? and the consensus seems to be that returning a simple string as JSON is legal, but many implementations don't yet support this.
对JSON.NET来说这是真的吗?有什么变通办法来处理可能包含简单类型而不仅仅是对象和数组的反序列化JSON?
Is this true for JSON.NET? What are the workarounds to handle deserializing JSON that might contain simple types and not just objects and arrays?
这似乎工作正常,我缺少什么吗?
This seems to work fine, am I missing something?
dynamic dyn;
dyn = GetObjectFromJSON("{ \"name\": \"john\", \"age\": 32 }");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("[ \"a\", \"b\", \"c\" ]");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("just a string");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("35");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON("true");
Debug.WriteLine((string)Convert.ToString(dyn));
dyn = GetObjectFromJSON(null);
Debug.WriteLine((Object)dyn ?? "(null)");
和
private Object GetObjectFromJSON(string jsonString)
{
if (String.IsNullOrEmpty(jsonString))
{
return null;
}
dynamic jsonResponse;
jsonString = jsonString.Trim();
if (jsonString.StartsWith("{") || jsonString.StartsWith("["))
{
// object or array
jsonResponse = JsonConvert.DeserializeObject(jsonString);
}
else
{
// some literal value
double d;
bool b;
if (Double.TryParse(jsonString, out d))
{
return d;
}
else if (bool.TryParse(jsonString, out b))
{
return b;
}
else
{
// not null, not an object, not an array, not a number, and not a boolean, so it's a string
jsonResponse = jsonString;
}
}
return jsonResponse;
}
推荐答案
看下面的电话:
dynamic dyn = JsonConvert.DeserializeObject("just a string");
这不是反序列化"just a string"
,而是反序列化just a string
(请注意字符串被""
包围).
This isn't deserializing "just a string"
it is deserializing just a string
(notice the string is surrounded by ""
).
如果我们查看JSON的规范,那么唯一不受该范围限制的有效字母字符序列""
是true
,false
和null
.
If we look at the spec for JSON, the only valid alpha character sequences that are not bounded by ""
are true
, false
, and null
.
如果要反序列化字符串,则需要确保它是规范定义的有效字符串.这应该是有效的反序列化调用:
If we want to deserialize a string, we need to make sure it is a valid string as defined by the spec. This should be a valid deserialization call:
dynamic dyn = JsonConvert.DeserializeObject("\"just a string\"");
查看您之前的问题 Java Jersey JSON服务不返回带引号的字符串?,我注意到您返回的是Object
类型:
Looking at your previous question Java Jersey JSON service doesn't return quoted string?, I noticed you are returning an Object
type:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object interpretationJson() {
String o = "a simple string";
return o;
}
我对Jersey没有任何经验,但是框架可能无法解释通用Object
.也许如果您使用String
返回类型,结果会有所不同吗?从该问题得到的公认答案看来,情况并非如此?
I do not have any experience with Jersey, but perhaps the framework has trouble interpreting the generic Object
. Perhaps if you used a String
return type the results would be different? From the accepted answer from that question it does not seem to be the case?
也许像下面这样的解决方案,添加""
并更改返回类型,是否合适?
Maybe a solution like the following, adding the ""
and changing the return type, would be appropriate?
@GET
@Produces(MediaType.APPLICATION_JSON)
public String interpretationJson() {
String o = "\"a simple string\"";
return o;
}
其结果应可反序列化.
这篇关于C#解析可能具有简单类型的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!