java json和对象互转
开发过程中遇到一些对象转string和string转对象的问题,浪费了很久,现在用的熟练些了,总结如下:
1.字符串尽量定义成json可解析的,如{"name":"a","param":"b"},而不是{"a":"b"}
2.用到开源项目:fastjson
需要引入:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.23</version>
</dependency>
import com.alibaba.fastjson.JSON;
使用方法:
1.string转对象:
string:str=
[{ "name": "HBaseService:v1", "clusters": [{ "name": "5u", "params": { "zk": "xxx.xxx.xxx.xxx", "port": "2180" }, "methods": [{ "name": "sayhello", "permission": true, "qps": 188 }, { "name": "sayhello", "permission": true, "qps": 188 }, { "name": "sayhello", "permission": true, "qps": 188 }] }, { "name": "6u", "params": { "name": "zk", "value": "xxxx:2180" }, "methods": [{ "name": "sayhello", "permission": true, "qps": 188 }, { "name": "sayhello", "permission": true, "qps": 188 }, { "name": "sayhello", "permission": true, "qps": 188 }] }] }]
转对象,先定义成几个类:
1.clusterinfo 其中包含变量name, params, List<MethodInfo>
2.methodInfo 其中包含变量name,permission,qps等
转对象:
JSONArray jsonArray = JSON.parseArray(str);
String new_str = jsonArray.get(i).toString();
logger.info("new_str:" + new_str);
ServiceInfo serviceInfo = JSON.parseObject(new_str, ServiceInfo.class);//转对象
2.对象转json:
List<ServiceConfigInfo> serviceConfigInfos = new ArrayList<ServiceConfigInfo>();
serviceConfigInfos.add(hbaseServiceImpl.hbaseContent());
JSON.toJSONString(serviceConfigInfos);//转string
好处:解析比较方便
劣处:需要定义多层类结构