我使用 Json.NET ( http://james.newtonking.com/projects/json/help/ ) 作为一种从服务器序列化和反序列化 JSON 的方法。假设我有以下 JSON 对象:
{
"user" : {
"name" : "Bob",
"age" : 35
},
"location" : "California"
}
我能找到将其反序列化为 native 类型的唯一方法是使用自定义 DTO,如下所示:
string jsonString = ""; // json string from above
Response result = JsonConvert.DeserializeObject<Response> (jsonString);
Response 类看起来像这样:
public class Response
{
[JsonProperty("user")]
public UserResponse User { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
}
public class UserResponse
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public int Age { get; set; }
}
我想将其反序列化为 native 类型,但我所处的环境并不总是知道 JSON 字符串会是什么样子...所以当我不确切知道时很难使用自定义 DTO我正在做的事情。如果我不将任何类传递给 JsonConvert.DeserializeObject(),那么我最终会得到 Json.NET 类型,而不是像字符串、整数等 native 类型。关于如何解决这个问题的任何建议?我应该改用其他 JSON 库吗?
谢谢!
最佳答案
这不会解决您所有的问题(那是不可能的),但这里有一个解决方案,可以让您使用有关返回内容的有限信息来解析 json。
在外层,您创建一个名为 Vehicle 的对象。这包含汽车、船和飞机。您正在请求一些 Vehicle,但您不知道它是 Car、Boat 还是 Plane(请注意,这可以轻松扩展以处理一系列 Vehicles 或许多其他更复杂的响应)。在架构中,您有一些选项,例如;
"id": "vehicle.schema.json",
"type": "object",
"required": true,
"additionalProperties": false,
"properties": {
"Car": {
"type": "object",
"required": false
//other properties
},
"Boat": {
"type": "object",
"required": false
//other properties
},
"Plane": {
"type": "object",
"required": false
//other properties
}
以上是您要添加到项目中的架构文件。如果你想要其中的几个,只需将更多元组添加到下面的 _schemaTypes 数组即可。
// code to set up your schema
// Associate types to their JsonSchemas. Order matters here.
// After each parse, the schema is added to resolver, which is used in subsequent parses.
_schemaTypes = new[]
{
Tuple.Create(typeof(Vehicle), "vehicle.schema.json"),
}
.ToDictionary(
x => x.Item1,
x => JsonSchema.Parse(
File.ReadAllText(
Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath ?? "", @"Serialization\Schemas\") + x.Item2),
resolver));
//method to return your deserialized object
public T Deserialize<T>(IRestResponse response)
{
var schema = _schemaTypes[typeof(T)];
T result = _serializer.Deserialize<T>(
new JsonValidatingReader(
new JsonTextReader(
new StringReader(response.Content)))
{
Schema = schema
});
return result;
}
现在,在您解析响应后,您将拥有一个更通用的对象,您可以从那里编写一些代码来确定返回的更具体的对象是什么。我正在使用这种类型的方法来解析 json,它具有多个级别的嵌套对象和对象数组,并且非常有效。
关于c# - Json.NET 保留 native 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13316962/