net.sf.json解析字符串(普通方式)

json-lib-2.3-jdk15.jar

commons-beanutils.jar

commons-lang-2.6.jar

commons-logging-1.1.1.jar

ezmorph-1.0.6.jar

测试用例


package test;



import java.util.Iterator;
import org.junit.Test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class test {
    
    @Test
    public void netSfJson() {
        String jsonStr = "{\r\n" + "\"name\":\"jarWorker\",\r\n" + "\"sex\":\"男\",\r\n" + "\"age\":26,\r\n"
                + "\"love\":[{\"hobby\":\"足球\",\"color\":\"White\"},{\"hobby\":\"篮球\",\"color\":\"Brown\"},{\"hobby\":\"\",\"color\":\"Yellow\"}],\r\n"
                + "\"goodAt\":\"Java\"\r\n" + "}";

        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        String name = jsonObject.getString("name");
        String sex = jsonObject.getString("sex");
        String age = jsonObject.getString("age");
        String goodAt = jsonObject.getString("goodAt");
        System.out.println("sex===" + sex);
        System.out.println("name===" + name);
        System.out.println("age===" + age);
        System.out.println("goodAt===" + goodAt);
        System.out.println("==========分割线===========");
        String love = jsonObject.getString("love");// 第一种方式
        JSONArray jsonArray = JSONArray.fromObject(love);// 跟上面是组合
        // JSONArray jsonArray= jsonObject.getJSONArray("love");第二种方式获得JSONArray
        jsonArray.get(0);// get(int index);按下标获得JSONObject
        Iterator it = jsonArray.iterator();
        while (it.hasNext()) {
            JSONObject obj = it.next();
            System.out.println("==============JSONObject=========");
            String hobby = obj.getString("hobby");
            String color = obj.getString("color");
            System.out.println("hobby===" + hobby);
            System.out.println("color===" + color);
        }
    }
}

Console:输出


sex===男
name===jarWorker
age===26
goodAt===Java
==========分割线===========
==============JSONObject=========
hobby===足球
color===White
==============JSONObject=========
hobby===篮球
color===Brown
==============JSONObject=========
hobby===
color===Yellow

你可能感兴趣的:(net.sf.json解析字符串(普通方式))