Parsing JSON data using Json-lib

Source: Internet
Author: User

1, first of all to understand a few concepts

JSON object, JSON array, JSON string

JSON objects can be represented by jsonobject

The JSON array can be represented by Jsonarray

A JSON string is just a string of type

And then look at the following code that's a lot easier.

Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;


Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;


public class Test {
public static void Main (string[] args) {
The list collection transforms the JSON array (consistent with the array)
list<string> list = new arraylist<string> ();
List.add ("a");
List.add ("B");
Jsonarray Jsonarray = jsonarray.fromobject (list);
System.err.println (Jsonarray.tostring ());
Map Collections Convert JSON objects
map<string, string> map = new hashmap<string, string> ();
Map.put ("1", "1");
Map.put ("2", "2");
Jsonobject jsonobject = jsonobject.fromobject (map);
System.out.println (Jsonobject.tostring ());
Converts the map collection to a JSON array (JavaBean is consistent with the map type)
Jsonarray jsonArray2 = jsonarray.fromobject (map);
System.out.println (Jsonarray2.tostring ());
General data (JSON string) converted to JSON
Jsonarray jsonArray3 = Jsonarray.fromobject ("[' 1 ', ' 2 ', ' 4 ']");
System.out.println (JSONARRAY3);

}
}

More complex conversions are based on the underlying conversions.

An array object that has recently been used in a project to convert a JSON string to a custom bean

First, convert the string to a JSON array, and then use the Jsonarray.tostring method to

Converts the specified JSON array to the corresponding custom Bean object

String users = Request.getparameter ("users");

Jsonarray Jsonarray = jsonarray.fromobject (users);


User[]users2 = (user[]) Jsonarray.toarray (Jsonarray, User.class);


Parsing JSON data using Json-lib

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.