Java ArrayList to JSON object go JSON

Source: Internet
Author: User

The introduction of related packages, the package used here is net.sf.json-lib:json-lib:2.4, but the introduction of a bit of a pit, the package has two versions, jdk1.5 and jdk1.4, the introduction of the time to add the corresponding JDK version number, or not to introduce success.

Gradle is used here, so add a line in the dependencies

Compile "net.sf.json-lib:json-lib:2.4:jdk15"

If you write compile "net.sf.json-lib:json-lib:2.4", then you cannot introduce success.

The following code shows how to turn ArrayList into JSON or how to turn a Java object into JSON

public class Javaobject{private String Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;}} @Testpublic void Arraylist2jsonandobject2json () {Javaobject javaobjecta = new Javaobject (); Javaobjecta.setname ("A"); Javaobject JAVAOBJECTB = new Javaobject (); Javaobjectb.setname ("B"); list<javaobject> javaobjectlist = new arraylist<> (); Javaobjectlist.add (javaobjecta); javaObjectList.add (JAVAOBJECTB); System.out.println (Jsonobject.fromobject (javaobjecta)); System.out.println (Jsonarray.fromobject (Javaobjectlist));}

The core approach is

System.out.println (Jsonobject.fromobject (javaobjecta)); System.out.println (Jsonarray.fromobject (javaobjectlist));

The result of the output is

{"Name": "A"} [{"Name": "A"},{"name": "B"}]


This article from "Dream do not know is a guest" blog, reproduced please contact the author!

Java ArrayList to JSON object go JSON

Related Article

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.