我有一些模型类,比如CustomerProduct等.在我的项目中,有几个字段和它们的setter-getter方法,我需要在客户端和服务器之间来回切换exchange objects of these classes as a JSONObject via Sockets.

Is there any way I can create JSONObject directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.

例子:

Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....

我将JSON对象创建为:

JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.

Which gets me something like:

{"name":"Foo Bar","city":"Atlantis"...}

Please note that, in some of my model classes, certain properties are itself an object of other model class. Such as:

Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);

In a case like above, as I'd expect, the yielded JSON object would be:

{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}

我知道我可以在每个模型类中创建大约toJSONString()个,然后创建JSON友好的字符串并对其进行操作,但在我以前用Java创建RESTful服务的经验中(这完全与这个问题无关),我可以使用@Produces(MediaType.APPLICATION_JSON)从服务方法返回JSON字符串,并让该方法返回model类的对象.所以它产生了JSON字符串,我可以在客户端使用它.

I was wondering if it's possible to get similar behavior in current scenario.

推荐答案

Google GSON人做到了这一点;我在几个项目中使用过它,它很简单,效果很好.它可以在不需要干预的情况下对简单对象进行翻译,但也有一种机制可以定制翻译(在两个方向上).

Gson g = ...;
String jsonString = g.toJson(new Customer());

Json相关问答推荐

对一些JSON模式验证的混淆

jq: Select 何时来自另一个数组的值与此 json 中的值匹配

Shell脚本空格转义

JOLT 在 struct 体中间添加一个 JSON 字段

如何使用 gson 将数据保存在 json 文件中?

Jackson 的@JsonView、@JsonFilter 和 Spring

如何在golang中获取 struct 的json字段名称?

什么是类型和类型令牌?

Jackson Scala 模块的小例子?

在 JSON.stringify() 的输出中隐藏空值

将文件发送到 Rails JSON API

使用杰克逊创建一个 json 对象

如何在 Django JSONField 数据上聚合(最小/最大等)?

Peewee 模型转 JSON

as_json 没有在关联上调用 as_json

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

字符串格式 JSON 字符串给出 KeyError

PHP json_encode json_decode UTF-8

仅使用字符串和值解析 JSON 对象

将 Pandas 数据框转换为嵌套 JSON