Java JSON and object cross-transfer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.