Kus*_*hal 29 java sockets json
我的项目中有一些模型类,比如Customer,Product等等,它们有几个字段和它们的setter-getter方法,我需要通过套接字将这些类的对象作为JSONObject与客户端和服务器进行交换.
有没有什么方法可以JSONObject直接从模型类的对象创建,使对象的字段成为键,该模型类对象的值成为此JSONObject的值.
例:
Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....
Run Code Online (Sandbox Code Playgroud)
我创建JSON对象为:
JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.
Run Code Online (Sandbox Code Playgroud)
这让我有点像:
{"name":"Foo Bar","city":"Atlantis"...}
Run Code Online (Sandbox Code Playgroud)
请注意,在我的一些模型类中,某些属性本身就是其他模型类的对象.如:
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
Run Code Online (Sandbox Code Playgroud)
在上面这样的情况下,正如我所期望的那样,产生的JSON对象将是:
{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}
Run Code Online (Sandbox Code Playgroud)
我知道我可以创建类似于toJSONString()每个模型类的东西并且创建并操作它的JSON友好字符串,但是在我之前使用Java创建RESTful服务的经验中(这完全脱离了这个问题的上下文),我可以返回通过使用服务方法的JSON字符串@Produces(MediaType.APPLICATION_JSON)并具有返回模型类的对象的方法.所以它产生了我可以在客户端使用的JSON字符串.
我想知道它是否有可能在当前场景中获得类似的行为.
任何帮助或建议表示赞赏.谢谢.
Ern*_*ill 37
谷歌GSON做到了这一点; 我已经在几个项目中使用它,它很简单,效果很好.它可以在没有干预的情况下对简单对象进行翻译,但也有一种机制可以自定义翻译(在两个方向上).
Gson g = ...;
String jsonString = g.toJson(new Customer());
Run Code Online (Sandbox Code Playgroud)
ale*_*y28 19
你可以使用Gson:
Maven依赖:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Java代码:
Customer customer = new Customer();
Product product = new Product();
// Set your values ...
Gson gson = new Gson();
String json = gson.toJson(customer);
Customer deserialized = gson.fromJson(json, Customer.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86434 次 |
| 最近记录: |