我有一些模型类,比如Customer
、Product
等.在我的项目中,有几个字段和它们的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.