REST API 包装器设计:将动态 json 返回为 JSON.NET JObject/JArray [英] REST API wrapper design: returning dynamic json as JSON.NET JObject / JArray

查看:19
本文介绍了REST API 包装器设计:将动态 json 返回为 JSON.NET JObject/JArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 RESTful JSON API 编写 C# 包装器,并使用 Json.NET 反序列化传入 json 到强类型对象.但是传入的 json 中的一些属性是高度动态的,它将是一些具有不同数量和类型的属性的 json 对象.我目前的解决方案是,我将动态 json 属性映射到 C# 类中的 Dictionary(嵌套字典),并编写自定义 JsonConverter 将动态 json 转换为嵌套字典.我的班级是这样的:

I am writing a C# wrapper for a RESTful JSON API, and using Json.NET to deserialize the incoming json to strongly typed object. but a few properties in the incoming json are highly dynamic, it will be some json object with different number and type of properties. My current solution is, I mapped the dynamic json property to Dictionary<string, object> (Nested dictionary) in my C# class,and write Custom JsonConverter to convert dynamic json to Nested dictionary. My class look like this:

public class Item
{
  [JsonProperty("item_id")]
  public int ItemId { get; set; }

  [JsonProperty("type")]
  public string Type { get; set; }

  //Property to map dynamic json object
  [JsonProperty("data")]
  public Dictionary<string, object> Data { get; set; }
}

成功了.

问题是,对于最终用户来说,从这个嵌套字典中访问数据是非常困难的,如果不在 Visual Studio 中调试,我们甚至无法看到数据的结构.现在我打算使用 JObjectJArray 而不是嵌套字典.这样我们只需调用ToString方法就可以看到数据的结构(将原始json数据输出为字符串),并且该类型具有LINQ支持,以便用户可以轻松访问数据.

The problem is, its very difficult to to access data from this nested dictionary for the end users, we can't even see what is the structure of data without debugging it in Visual studio. Now i am planning to use JObject or JArray instead of nested dictionary. So that we can see the structure of data by just calling ToString method (Will output the original json data as string) as well as this types have LINQ support so that users can access data from it easily.

考虑到 JObject,这是一个很好的做法吗?JArray 类型都取决于在第三方库上(无论如何,Json.NET 是我的库的依赖项,因为我将它用于 json 序列化).或者还有其他方法可以做到这一点?

Is this a good practice use this, considering JObject and JArray types both depend on a third party library (Anyway Json.NET is a dependency for my library because i am using it for json serialization) . Or there some other ways to do this ?

推荐答案

你应该使用 ExpandoObjectConverter 代替.

您需要像 dynamic 一样输入 IDictionary 并使用 [JsonConverter(typeof(ExpandoObjectConverter))]<装饰整个属性/代码>.

You need to type your IDictionary<string, object> as just dynamic and decorate the whole property with [JsonConverter(typeof(ExpandoObjectConverter))].

一个有趣的细节是 ExpandoObject 也实现了 IDictionary,但是当你用 dynamic 键入它时,你可以访问关联的属性和普通属性一样!;)

One interesting detail is ExpandoObject also implements IDictionary<string, object>, but when you type it with dynamic, you can access associated properties like regular ones! ;)

这篇关于REST API 包装器设计:将动态 json 返回为 JSON.NET JObject/JArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆