data转JSONObject
时间: 2024-01-04 16:02:20 浏览: 86
要将Date类型的数据转换为JSONObject,可以使用JsonConfig类来注册一个JsonValueProcessor,然后使用JSONObject.fromObject()方法进行转换。首先,创建一个JsonConfig对象,并使用registerJsonValueProcessor()方法注册一个处理Date类型的JsonValueProcessor。然后,创建一个User对象,并设置其属性,包括Date类型的属性。最后,使用JSONObject.fromObject()方法将User对象转换为JSONObject。以下是示例代码:
```
User user = new User();
user.setId(1000);
user.setName("万诗强");
user.setBirthday(new Date());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject jsonObject = JSONObject.fromObject(user, jsonConfig);
System.out.println(jsonObject.toString());
```
运行结果会输出类似于以下内容的JSONObject:
```
{"birthday":"2013-10-24 11:10:50","id":1000,"name":"万诗强"}
```
注意,JsonConfig和JsonDateValueProcessor类都是来自net.sf.json.JsonConfig包。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [解决Java对象中date类型被解析为JSON数组问题](https://blog.csdn.net/psl1234554321/article/details/126024027)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [带有Data类型的bean对象与JSON对象的转换](https://blog.csdn.net/kingwsq/article/details/12995195)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文