The development process encountered some object to string and string to the object of the problem, wasted a long time, now with the proficiency of some, summarized as follows:
1. The string should be defined as JSON resolvable, such as {"Name": "A", "param": "B"}, not {"A": "B"}
2. Use the Open source project: Fastjson
Need to introduce:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.23</version>
</dependency>
Import Com.alibaba.fastjson.JSON;
How to use:
1.string to object:
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": "Sayh Ello "," permission ": True," QPS ": 188}, {" Name ":" SayHello "," Permiss Ion ": True," QPS ": 188}]}]}]
go to the object, first defined into several classes:
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);//Turn to Object
2. Object to JSON:
list<serviceconfiginfo> Serviceconfiginfos = new arraylist<serviceconfiginfo> ();
Serviceconfiginfos.add (Hbaseserviceimpl.hbasecontent ());
Json.tojsonstring (Serviceconfiginfos);//Turn string
Benefits: Easy to parse
Inferior place: Need to define multi-layer class structure
Java JSON and object cross-transfer