Use json-lib to parse json data

Source: Internet
Author: User

Use json-lib to parse json data

1. First, we need to understand several concepts.

Json object, json array, json string

Json objects can be represented by JsonObject.

Json array can be represented by JsonArray

A json String is a String of the String type.

The following code is much simpler.

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 ){
// Convert the List set to a json array (consistent with the array)
List List = new ArrayList ();
List. add ("");
List. add ("B ");
JSONArray jsonArray = JSONArray. fromObject (list );
System. err. println (jsonArray. toString ());
// Converts the map set to a json object.
Map Map = new HashMap ();
Map. put ("1", "1 ");
Map. put ("2", "2 ");
JSONObject jsonObject = JSONObject. fromObject (map );
System. out. println (jsonObject. toString ());
// Convert the map set to a json array (the javabean and map types are the same)
JSONArray jsonArray2 = JSONArray. fromObject (map );
System. out. println (jsonArray2.toString ());
// Convert general data (json string) to json
JSONArray jsonArray3 = JSONArray. fromObject ("['1', '2', '4']");
System. out. println (jsonArray3 );

}
}

More complex conversions are based on the above-mentioned basic transformations.

Recently, an array object used in the 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

Converts the specified json array to a custom bean object.

String users = request. getParameter ("users ");

JSONArray jsonArray = JSONArray. fromObject (users );


User [] users2 = (User []) JSONArray. toArray (jsonArray, User. class );/

 

 

 

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.