Java parsing JSON

Source: Internet
Author: User

A lot of the JSON construction and parsing tools are published in Java, where Org.json and json-lib are relatively simple, but there are some differences in the use of the two. The following first describes an example of how to construct and parse JSON data using Json-lib.

First, Introduction

Json-lib package is a Beans,collections,maps,java arrays and XML and JSON to convert the package, is mainly used to parse the JSON data, on its official website has detailed explanation, interested can go to research.

Second, download the jar package, you can go here to download http://down.51cto.com/data/2094833

Three, the introduction of JSON

1. Convert list collection to JSON method

List List = new ArrayList (), List.add ("first"), List.add ("second"); Jsonarray jsonArray2 = jsonarray.fromobject (list);

2. Map collection into JSON method

Map map = new HashMap (), Map.put ("name", "JSON"), Map.put ("bool", Boolean.true), map.put ("int", new Integer (1)), Map.put (" Arr ", new string[] {" A "," B "}), Map.put (" func "," function (i) {return this.arr[i];} "); Jsonobject JSON = jsonobject.fromobject (map);

3. Bean converted to JSON code

Jsonobject jsonobject = jsonobject.fromobject (New Jsonbean ());

4. Convert arrays into JSON code

boolean[] Boolarray = new boolean[] {true, false, true}; Jsonarray jsonArray1 = Jsonarray.fromobject (Boolarray);

5. Conversion of general data into JSON code

Jsonarray jsonArray3 = Jsonarray.fromobject ("[' json ', ' is ', ' easy ']");

6. Beans conversion to JSON code

List List = new ArrayList (); JsonBean2 jb1 = new JsonBean2 () Jb1.setcol (1); Jb1.setrow (1); Jb1.setvalue ("xx"); JsonBean2 jb2 = new JsonBean2 () Jb2.setcol (2); Jb2.setrow (2); Jb2.setvalue (""); List.add (JB1); List.add (JB2); Jsonarray ja = jsonarray.fromobject (list);

Iv. code Examples

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 importjava.util.ArrayList;import java.util.HashMap;importjava.util.List;importjava.util.Map;importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;publicclassjsonTest {    /**     * @param args     */    publicstaticvoidmain(String[] args) {                jsonTest.BuildJson();    }    /**     * 构造Json数据          * @return     */    publicstatic String BuildJson() {        // JSON格式数据解析对象        JSONObject jo = newJSONObject();        // 下面构造两个map、一个list和一个Employee对象        Map<String, String> map1 = new HashMap<String, String>();        map1.put("name""Alexia");        map1.put("sex""female");        map1.put("age""23");        Map<String, String> map2 = newHashMap<String, String>();        map2.put("name""Edward");        map2.put("sex""male");        map2.put("age""24");        List<Map> list = new ArrayList<Map>();        list.add(map1);        list.add(map2);        Employee employee = newEmployee();        employee.setName("wjl");        employee.setSex("female");        employee.setAge(24);        // 将Map转换为JSONArray数据        JSONArray ja1 = JSONArray.fromObject(map1);        // 将List转换为JSONArray数据        JSONArray ja2 = JSONArray.fromObject(list);        // 将Bean转换为JSONArray数据        JSONArray ja3 = JSONArray.fromObject(employee);        System.out.println("JSONArray对象数据格式:");        System.out.println(ja1.toString());        System.out.println(ja2.toString());        System.out.println(ja3.toString());        // 构造Json数据,包括一个map和一个Employee对象        jo.put("map", ja1);        jo.put("employee", ja2);        System.out.println("\n最终构造的JSON数据格式:");        System.out.println(jo.toString());        returnjo.toString();     }    /**     * 解析Json数据          * @param jsonString Json数据字符串     */    public staticvoidParseJson(String jsonString) {        // 以employee为例解析,map类似        JSONObject jb = JSONObject.fromObject(jsonString);        JSONArray ja = jb.getJSONArray("employee");         List<Employee> empList = newArrayList<Employee>();        // 循环添加Employee对象(可能有多个)        for(inti = 0; i < ja.size(); i++) {            Employee employee = newEmployee();            employee.setName(ja.getJSONObject(i).getString("name"));            employee.setSex(ja.getJSONObject(i).getString("sex"));            employee.setAge(ja.getJSONObject(i).getInt("age"));            empList.add(employee);        }        System.out.println("\n将Json数据转换为Employee对象:");        for(inti = 0; i < empList.size(); i++) {            Employee emp = empList.get(i);            System.out.println("name: " + emp.getName() + " sex: "                    + emp.getSex() + " age: "+ emp.getAge());        }    }    /**     * @param args     */    publicstaticvoidmain(String[] args) {        // TODO Auto-generated method stub        ParseJson(BuildJson());    }}

V. The results of the operation are as follows

Vi. comparison with Org.json

The use of Json-lib and Org.json is almost identical, with two points in theJava training organization rankings :

1. Org.json is much lighter than Json-lib, the former does not depend on any other jar packages, while the latter relies on ezmorph and Commons's lang, logging, Beanutils, collections, and other components

2. Json-lib in the construction of beans and parsing beans more convenient than Org.json, Json-lib can be directly with the bean conversion, and Org.json can not directly with the bean conversion and need map as a transit, if the bean to JSON data, first need to convert the bean to M The AP then turns the map into JSON, which is more cumbersome.

In short, or that sentence-suitable for their own is the best, we need to choose which method to use to resolve. Finally, we introduce two tools for parsing JSON data: One is online tool Jsonedit (http://braincast.nl/samples/jsoneditor/) and the other is Eclipse's plugin json Tree Analyzer, are very useful, recommended for everyone to use!

Java parsing JSON

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.