对象转换成json,使用传统的Stringbutld方式,个人感觉比较麻烦,于是采用jsonlib将对象转换成json对象的方式。
首先看看各种独享转换成Json对象后的格式:
Object 类型装换成Json {"code":"hello","message":"json","object":{"age":10,"name":"zhangs","pass":"123"}}
List 类型装换成Json ["hello","java"]
Map 类型装换成json [{"hello":110,"tig":90,"java":122,"kilty":221}]
Array 类型转换成json [1,2,3,4,5,6,7]
Lsit 存储对象装换 [{"autoIncrement":true,"columnuName":"id","dataTypeName":"VARCHAR","defaultValue":"10",
"isNull":0,"key":true,"precision":5,"scale":2}]
假设需要Json格式:
{
"columnInfo": [
{
"autoIncrement": true,
"columnuName": "id",
"dataTypeName": "VARCHAR",
"defaultValue": "10",
"isNull": 0,
"key": true,
"precision": 5,
"scale": 2
}
],
"tableName": "t_res"
}
首先定义一个类封装需要的数据,在定义一个类用来封装前台需要的json数据:
数据对象:
public class JsonPo { private String columnuName; private String dataTypeName; private boolean isKey; private boolean isAutoIncrement; private Integer isNull; private Integer precision; private String defaultValue; private Integer scale; public String getColumnuName() { return columnuName; } public void setColumnuName(String columnuName) { this.columnuName = columnuName; } public String getDataTypeName() { return dataTypeName; } public void setDataTypeName(String dataTypeName) { this.dataTypeName = dataTypeName; } public boolean isKey() { return isKey; } public void setKey(boolean isKey) { this.isKey = isKey; } public boolean isAutoIncrement() { return isAutoIncrement; } public void setAutoIncrement(boolean isAutoIncrement) { this.isAutoIncrement = isAutoIncrement; } public Integer getIsNull() { return isNull; } public void setIsNull(Integer isNull) { this.isNull = isNull; } public Integer getPrecision() { return precision; } public void setPrecision(Integer precision) { this.precision = precision; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public Integer getScale() { return scale; } public void setScale(Integer scale) { this.scale = scale; } } 显示对象: public class JsonVo { private String tableName; private List<JsonPo> columnInfo; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public List<JsonPo> getColumnInfo() { return columnInfo; } public void setColumnInfo(List<JsonPo> columnInfo) { this.columnInfo = columnInfo; } } 实现:
自己也不知道好不好用。。。。。。。。。。。。。。。不喜勿喷。。。。。。。public class Json_06 { public static void main(String[] args) { List<JsonPo> list = new ArrayList<JsonPo>(); JsonPo jp = new JsonPo(); jp.setColumnuName("id"); jp.setDataTypeName("VARCHAR"); jp.setKey(true); jp.setAutoIncrement(true); jp.setIsNull(0); jp.setPrecision(5); jp.setDefaultValue("10"); jp.setScale(2); list.add(jp); JSONArray jsonArray = JSONArray.fromObject(list); System.out.println(jsonArray.toString()); } }