码迷,mamicode.com
首页 > 编程语言 > 详细

Java类对象和Json数据之间的转换

时间:2015-11-16 19:23:19      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

表字段过多,不想分别保存到数据中,使用频率低,所以考虑使用Jave类 -- Json之间的数据转换。

 

1、类转换Json,并保存到数据

Attribute.java

技术分享
 1 /**
 2  * 属性数据结构
 3  *
 4  */
 5 public class Attribute {
 6 
 7     private static final long serialVersionUID = -1L;
 8 
 9     private Long attrId;
10 
11     private List<AttributeValue> attributeValues;
12 
13     private Long catid;
14 
15     private String cnName;
16 
17     private Boolean customizeImage;
18 
19     private Boolean customizeValue;
20 
21     private String enName;
22 
23     private String inputType;
24 
25     private Boolean keyAttr;
26 
27     private Boolean locator;
28 
29     private Long order;
30 
31     private Long parentValue;
32 
33     private Boolean required;
34 
35     private List<String> units;
Attribute.java

AttributeService.java

1 //转换成Json字符串
2 List<Attribute> attributes = response.getAttributes();
3 JSONArray jsonArray = JSONArray.fromObject(attributes);
4 //保存到数据中
5 this.Save(jsonArray.toString());

 

2、Json转换成类

AttributeService.java

1 //从数据库中获取Json属性
2 String jsonAttribute = this.getAttribute();
3 //转换成Json数组
4 JSONArray jsonAttr = JSONArray.fromObject(jsonAttribute );
5 //由于Attribute类中包含List<AttributeValue>,需要添加子集合
6 Map<String, Class> classMap = new HashMap<String, Class>();            
7 classMap.put("attributeValues", AttributeValue.class);  
8 //最后转换List对象完成
9 List<Attribute> listProductAttributes = (List<Attribute>)JSONArray.toList(jsonAttr, Attribute.class,classMap);

 

换一种思路来处理数据,这样做会更简单,对数据库的操作更方便,只是在数据库中不便阅读,页面端展示跟分表分字段存储没有任何区别。

 

Java类对象和Json数据之间的转换

标签:

原文地址:http://www.cnblogs.com/wls-blogs/p/4969569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!