java解析json字符串数据

      在www.json.org上公布了很多JAVA下的json构造和解析工具,其中org.json和json-lib比较简单,两者使用上差不多但还是有些区别。下面接着介绍用org.json构造和解析Json数据的方法示例。

      用json-lib构造和解析Json数据的方法详解请参见我上一篇博文:Java构造和解析Json数据的两种方法详解一

一、介绍

      org.json包是另一个用来beans,collections,maps,java arrays 和XML和JSON互相转换的包,主要就是用来解析Json数据,在其官网http://www.json.org/上有详细讲解,有兴趣的可以去研究。

二、下载jar依赖包

      可以去这里下载    http://download.csdn.net/detail/lanxuezaipiao/5440983

三、基本方法介绍

      由于org.json不能直接与bean进行转换,需要通过map进行中转,为了方便,我这里写了一个工具类JsonHelper,用于Json与Map、Bean的相互转换

复制代码
package com.json;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * 1:将JavaBean转换成Map、JSONObject
 * 2:将Map转换成Javabean
 * 3:将JSONObject转换成Map、Javabean
 * 
 * @author Alexia
*/

public class JsonHelper {

/**
     * 将Javabean转换为Map
     * 
     * @param javaBean
     *            javaBean
     * @return Map对象
*/
public static Map toMap(Object javaBean) {

        Map result = new HashMap();
        Method[] methods = javaBean.getClass().getDeclaredMethods();

for (Method method : methods) {

try {

if (method.getName().startsWith("get")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("get") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);

                    Object value = method.invoke(javaBean, (Object[]) null);
                    result.put(field, null == value ? "" : value.toString());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

return result;

    }

/**
     * 将Json对象转换成Map
     * 
     * @param jsonObject
     *            json对象
     * @return Map对象
     * @throws JSONException
*/
public static Map toMap(String jsonString) throws JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);

        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;

while (iterator.hasNext()) {

            key = (String) iterator.next();
            value = jsonObject.getString(key);
            result.put(key, value);

        }
return result;

    }

/**
     * 将JavaBean转换成JSONObject(通过Map中转)
     * 
     * @param bean
     *            javaBean
     * @return json对象
*/
public static JSONObject toJSON(Object bean) {

return new JSONObject(toMap(bean));

    }

/**
     * 将Map转换成Javabean
     * 
     * @param javabean
     *            javaBean
     * @param data
     *            Map数据
*/
public static Object toJavaBean(Object javabean, Map data) {

        Method[] methods = javabean.getClass().getDeclaredMethods();
for (Method method : methods) {

try {
if (method.getName().startsWith("set")) {

                    String field = method.getName();
                    field = field.substring(field.indexOf("set") + 3);
                    field = field.toLowerCase().charAt(0) + field.substring(1);
                    method.invoke(javabean, new Object[] {

                    data.get(field)

                    });

                }
            } catch (Exception e) {
            }

        }

return javabean;

    }

/**
     * JSONObject到JavaBean
     * 
     * @param bean
     *            javaBean
     * @return json对象
     * @throws ParseException
     *             json解析异常
     * @throws JSONException
*/
public static void toJavaBean(Object javabean, String jsonString)
throws ParseException, JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);

        Map map = toMap(jsonObject.toString());

        toJavaBean(javabean, map);

    }

}
复制代码

四、演示示例

这里以基本的几个常用方法进行测试

 

复制代码
package com.json;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 使用json-lib构造和解析Json数据
 * 
 * @author Alexia
 * @date 2013/5/23
 * 
*/
public class OrgJsonTest {

/**
     * 构造Json数据
     * 
     * @return
     * @throws JSONException
*/
public static String BuildJson() throws JSONException {

// JSON格式数据解析对象
        JSONObject jo = new JSONObject();

// 下面构造两个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 = new HashMap<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 = new Employee();
        employee.setName("wjl");
        employee.setSex("female");
        employee.setAge(24);

// 将Map转换为JSONArray数据
        JSONArray ja = new JSONArray();
        ja.put(map1);

        System.out.println("JSONArray对象数据格式:");
        System.out.println(ja.toString());

// 将Javabean转换为Json数据(需要Map中转)
        JSONObject jo1 = JsonHelper.toJSON(employee);

        System.out.println("\n仅含Employee对象的Json数据格式:");
        System.out.println(jo1.toString());

// 构造Json数据,包括一个map和一个含Employee对象的Json数据
        jo.put("map", ja);
        jo.put("employee", jo1.toString());
        System.out.println("\n最终构造的JSON数据格式:");
        System.out.println(jo.toString());

return jo.toString();

    }

/**
     * 解析Json数据
     * 
     * @param jsonString
     *            Json数据字符串
     * @throws JSONException
     * @throws ParseException
*/
public static void ParseJson(String jsonString) throws JSONException,
            ParseException {

        JSONObject jo = new JSONObject(jsonString);
        JSONArray ja = jo.getJSONArray("map");

        System.out.println("\n将Json数据解析为Map:");
        System.out.println("name: " + ja.getJSONObject(0).getString("name")
+ " sex: " + ja.getJSONObject(0).getString("sex") + " age: "
                + ja.getJSONObject(0).getInt("age"));

        String jsonStr = jo.getString("employee");
        Employee emp = new Employee();
        JsonHelper.toJavaBean(emp, jsonStr);

        System.out.println("\n将Json数据解析为Employee对象:");
        System.out.println("name: " + emp.getName() + " sex: " + emp.getSex()
+ " age: " + emp.getAge());

    }

/**
     * @param args
     * @throws JSONException
     * @throws ParseException
*/
public static void main(String[] args) throws JSONException, ParseException {
// TODO Auto-generated method stub

        ParseJson(BuildJson());
    }

}
复制代码

 

 

运行结果如下

五、与json-lib比较

      json-lib和org.json的使用几乎是相同的,我总结出的区别有两点:

      1. org.json比json-lib要轻量得多,前者没有依赖任何其他jar包,而后者要依赖ezmorph和commons的lang、logging、beanutils、collections等组件

      2. json-lib在构造bean和解析bean时比org.json要方便的多,json-lib可直接与bean互相转换,而org.json不能直接与bean相互转换而需要map作为中转,若将bean转为json数据,首先需要先将bean转换为map再将map转为json,比较麻烦。

      总之,还是那句话—适合自己的才是最好的,大家要按需选取使用哪种方法进行解析。最后给大家介绍两款解析Json数据的工具:一是在线工具JSONEdit(http://braincast.nl/samples/jsoneditor/);另一个是Eclipse的插件JSON Tree Analyzer,都很好用,推荐给大家使用!



在网页中想后台传递多个数据时,有时数据还是多个动态列表,数据很复杂时,JavaScript程序员喜欢把他们作为json串进行处理,后台收到后需要对json字符串进行解析,幸好有JSON-lib,这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
下载地址:http://json-lib.sourceforge.net/

public class Test {

/**

* @param args

* @author wen

*/

public static void main(String[] args) {

// test1();

// test2();

String json = “{1:{1:{jhinfo:['计划一','知行网,'www.zhixing123.cn'],jhrate:['1-5:10.0','6-100:5.0/1']},2:{jhinfo:['计划二',''知行网,'www.zhixing123.cn'],],jhrate:['1-100:100.0']},3:{jhinfo:['计划三',''知行网,'www.zhixing123.cn'],],jhrate:['1-100:150.0/7']}},2:{4:{jhinfo:['年计划',''知行网,'www.zhixing123.cn'],],jhrate:['365-365:1000.0']}}}”;

try {

JSONObject jsonObject = JSONObject.fromObject(json);

String name = jsonObject.getString(“1″);

String address = jsonObject.getString(“2″);

System.out.println(“name is:” + name);

System.out.println(“address is:” + address);

Iterator it=jsonObject.keys();

while (it.hasNext()){

System.out.println(jsonObject.get(it.next()));

}

} catch (JSONException e) {

e.printStackTrace();

}

}

/**

* json对象字符串转换

* @author wen

*/

private static void test2() {

String json = “{‘name’: ‘亲亲宝宝’,'array’:[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],’address’:'亲亲宝宝’}”;

try {

JSONObject jsonObject = JSONObject.fromObject(json);

String name = jsonObject.getString(“name”);

String address = jsonObject.getString(“address”);

System.out.println(“name is:” + name);

System.out.println(“address is:” + address);

JSONArray jsonArray = jsonObject.getJSONArray(“array”);

for (int i = 0; i < jsonArray.size(); i++) {

System.out.println(“item ” + i + ” :” + jsonArray.getString(i));

}

} catch (JSONException e) {

e.printStackTrace();

}

}

/**

* json数组 转换,数组以[开头

* @author wen

*/

private static void test1() {

boolean[] boolArray = new boolean[]{true,false,true};

JSONArray jsonArray1 = JSONArray.fromObject( boolArray );

System.out.println( jsonArray1 );

// prints [true,false,true]

List list = new ArrayList();

list.add( “first” );

list.add( “second” );

JSONArray jsonArray2 = JSONArray.fromObject( list );

System.out.println( jsonArray2 );

// prints ["first","second"]

JSONArray jsonArray3 = JSONArray.fromObject( “['json','is','easy']” );

System.out.println( jsonArray3 );

// prints ["json","is","easy"]

}


一、   JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。
 Json建构于两种结构:
     1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如:     
        {
            “name”:”jackson”,
            “age”:100
         }

2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
     {
        “students”:
        [
            {“name”:”jackson”,“age”:100},
            {“name”:”michael”,”age”:51}
        ]
     }
二、java解析JSON步骤
    A、服务器端将数据转换成json字符串
      首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:http://json-lib.sourceforge.net/)

然后将数据转为json字符串,核心函数是:
 public static String createJsonString(String key, Object value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }
B、客户端将json字符串转换为相应的javaBean
   1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)
public class HttpUtil
{

    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}
2、获取javaBean
    public static Person getPerson(String jsonStr)
    {
        Person person = new Person();
        try
        {// 将json字符串转换为json对象
            JSONObject jsonObj = new JSONObject(jsonStr);
            // 得到指定json key对象的value对象
            JSONObject personObj = jsonObj.getJSONObject("person");
            // 获取之对象的所有属性
            person.setId(personObj.getInt("id"));
            person.setName(personObj.getString("name"));
            person.setAddress(personObj.getString("address"));
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return person;
    }

    public static List<Person> getPersons(String jsonStr)
    {
        List<Person> list = new ArrayList<Person>();

        JSONObject jsonObj;
        try
        {// 将json字符串转换为json对象
            jsonObj = new JSONObject(jsonStr);
            // 得到指定json key对象的value对象
            JSONArray personList = jsonObj.getJSONArray("persons");
            // 遍历jsonArray
            for (int i = 0; i < personList.length(); i++)
            {
                // 获取每一个json对象
                JSONObject jsonItem = personList.getJSONObject(i);
                // 获取每一个json对象的值
                Person person = new Person();
                person.setId(jsonItem.getInt("id"));
                person.setName(jsonItem.getString("name"));
                person.setAddress(jsonItem.getString("address"));
                list.add(person);
            }
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }


转载请注明本文地址: java解析json字符串数据


猜你喜欢

转载自blog.csdn.net/wangchaoqi1985/article/details/80305934