Java处理JSON

JSON使用方法

Json在数据传输中很好用,原因是JSON 比 XML 更小、更快,更易解析。在Java程序中,如何使用处理JSON,现在有很多工具可以处理,比较流行常用的是google的gson和alibaba的fastjson,具体使用如下:

1、读取json然后处理

class ReadJSON
{
    public static void main(String[] args)
    {
        String jsonStr = "{ \"one\":\"one\", \"two\":[{ \"two_1_1\":2.11, \"two_1_2\":2.12}, { \"two_2_1\":\"2.21\" } ], \"three\":[\"abc\",false], \"four\":{\"four_1\":4.1, \"four_2\":4.2 } }";
        // one:简单类型
        // two:对象数组(最复杂)
        // three:数组类型
        // four:对象类型

        jsonGoogle(jsonStr);
        jsonAlibaba(jsonStr);
    }

    // gosn读取处理json
    public static void jsonGoogle(String jsonStr)
    {
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = (JsonObject) parser.parse(jsonStr);

        String one = jsonObj.get("one").getAsString();
        System.out.println(one);// one

        JsonArray twoObjArray = jsonObj.get("two").getAsJsonArray();
        System.out.println(twoObjArray);// [{"two_1_1":2.11,"two_1_2":2.12},{"two_2_1":"2.21"}]
        JsonObject twoObj = (JsonObject) twoObjArray.get(0);
        String two = twoObj.get("two_1_1").getAsString();// 可以当成string处理
        System.out.println(two);// 2.11

        JsonArray threeArray = jsonObj.get("three").getAsJsonArray();
        String three_1 = threeArray.get(0).getAsString();
        boolean three_2 = threeArray.get(1).getAsBoolean();
        System.out.println(three_1 + three_2);// abcfalse

        JsonObject fourObj = jsonObj.get("four").getAsJsonObject();
        double four_1 = fourObj.get("four_1").getAsDouble();
        System.out.println(four_1);// 4.1
    }

    // fastjson读取处理json
    public static void jsonAlibaba(String jsonStr)
    {
        JSONObject jsonObj = JSON.parseObject(jsonStr);

        String one = jsonObj.getString("one");
        System.out.println(one);// one

        JSONArray twoObjArray = jsonObj.getJSONArray("two");
        System.out.println(twoObjArray);// [{"two_1_1":2.11,"two_1_2":2.12},{"two_2_1":"2.21"}]
        JSONObject twoObj = twoObjArray.getJSONObject(1);
        String two_2 = twoObj.getString("two_2_1");
        System.out.println(two_2);// 2.21

        JSONArray threeArray = jsonObj.getJSONArray("three");
        String three_1 = threeArray.getString(0);
        boolean three_2 = threeArray.getBoolean(1);
        System.out.println(three_1 + three_2);// abcfalse

        JSONObject fourObj = jsonObj.getJSONObject("four");
        String four_1 = fourObj.getString("four_1");
        System.out.println(four_1);// 4.1
    }
}

  

2、写json

public class Person
{
    private String name;
    private int age;
    private double salary;
    private boolean hasBaby;
    private List<String> babyNames;
    // setter/getter/toString等
}
public class WriteJSON
{
    public static void main(String[] args)
    {
        writeJsonGoogle();
        writeJsonAlibaba();
    }

    // gson写json
    public static void writeJsonGoogle()
    {
        JsonObject jsonObj = new JsonObject();

        jsonObj.addProperty("one", "oneStr");
        jsonObj.addProperty("two", false);

        JsonObject threeObj = new JsonObject();
        threeObj.addProperty("three", 3);
        jsonObj.add("three", threeObj);

        JsonArray jsonArray = new JsonArray();
        JsonObject four_1 = new JsonObject();
        four_1.addProperty("four_1", 4.1);
        JsonObject four_2 = new JsonObject();
        four_2.addProperty("four_2", true);
        jsonArray.add(four_1);
        jsonArray.add(four_2);
        jsonObj.add("four", jsonArray);

        System.out.println(jsonObj.toString());
        // {"one":"oneStr","two":false,"three":{"three":3},"four":[{"four_1":4.1},{"four_2":true}]}
    }

    // fastjson写json
    public static void writeJsonAlibaba()
    {
        Map<String, Object> jsonMap = new TreeMap<String, Object>();
        jsonMap.put("one", "oneStr");
        jsonMap.put("two", false);

        Map<String, Object> threeObj = new HashMap<String, Object>();
        threeObj.put("three_1", "3.1");
        threeObj.put("three_2", 3.2);
        jsonMap.put("three", threeObj);

        JSONObject jsonObj = new JSONObject(jsonMap);
        List<String> babynames = new ArrayList<String>();
        babynames.add("abc");
        babynames.add("def");
        Person person = new Person("gusi", 12, 7000.00, true, babynames);
        jsonObj.put("four", person);

        jsonObj.put("five", 5);

        System.out.println(jsonObj.toJSONString());
        // {"five":5,"four":{"age":12,"babyNames":["abc","def"],"hasBaby":true,"name":"gusi","salary":7000},"one":"oneStr","three":{"three_1":"3.1","three_2":3.2},"two":false}
    }
}

 

3、对象类型和json的常用转换(包括gson和fastjson)

基础Object

public class Demo implements Serializable
{
    String name;
    int age;
    boolean man;

    public Demo()
    {
        super();
    }

    public Demo(String name, int age, boolean man)
    {
        super();
        this.name = name;
        this.age = age;
        this.man = man;
    }

    // setter/getter,千万不能忘了,不然fastjson不能设置值
    @Override
    public String toString()
    {
        return "Demo [name=" + name + ", age=" + age + ", man=" + man + "]";
    }

}

处理方式

//gson
Demo demo1 = new Demo("a", 1, false);
String json1 = new Gson().toJson(demo1);// JavaBean到String
System.out.println(json1);
Demo demo2 = new Gson().fromJson(json1, Demo.class);// String到JavaBean
System.out.println(demo2);
JsonObject jsonObj1 = (JsonObject) new JsonParser().parse(json1);// String到jsonObject
System.out.println(jsonObj1);
String json2 = jsonObj1.toString();// jsonObject到String
System.out.println(json2);

//fastjson
Demo demo3 = new Demo("b", 2, true);
String json3 = JSON.toJSONString(demo3);// JavaBean到String
System.out.println(json3);
Demo demo4 = JSON.parseObject(json3, Demo.class);// String到JavaBean
System.out.println(demo4);
JSONObject jsonObj2 = JSON.parseObject(json3);// String到jsonObject
System.out.println(jsonObj2);
String json4 = jsonObj2.toJSONString();// jsonObject到String
System.out.println(json4);
JSONObject jsonObj3 = (JSONObject) JSON.toJSON(demo3);// JavaBean到jsonObject
System.out.println(jsonObj3);

通过上面的方法,基本上就能处理绝大部分的json.

 

处理嵌套json格式的数据。。。 public static void main(String[] args) { // 官方API http://www.json.org/java/ /* 购物车中信息 goods_cart={cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}}; * **/ try{ String s0 = "{cart_1325036696007:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"b555bfj05d7dcg307h91323398584156",specsstr:"颜色:黑色 尺寸:L",price:4765,stock:15,count:6},cart_1325036702105:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100016_00948703_68.jpg",specs:"787a9f5he93chcifh951323398314484",specsstr:"颜色:黑色 尺寸:XL",price:4700.15,stock:12,count:1},cart_1325136643984:{goods_id:"100015",goods_name:"澳大利亚进口绵羊",goods_imgsrc:"http://192.168.1.180:7001//gwadmin/uploadimg/spxc/2011/12/9/100015_00399656_68.jpg",specs:"8466347bi6eia43hd6j1323398639859",specsstr:"颜色:灰色 尺寸:XL",price:4600,stock:3,count:1}};"; String s= java.net.URLDecoder.decode(s0, "utf-8"); System.out.println(s); JSONObject o = new JSONObject(s); System.out.println(o.get("cart_1325036696007")); //根据属性,获取值 System.out.println(o.toString()); //得到字符串 System.out.println(o.names().get(2)); //获取对象中第三组属性名 System.out.println(o.names().length()); //获取对象中属性个数 //System.out.println(o.names().getJSONArray(1)); //获取对象中属性个数 //names(jsonObjectName) 私有方法 获取该对象的所有属性名,返回成JSONArray。 //JSONObject.getNames(jsonObjectName) 静态方法 获取对象的所有属性名,返回成数组。 System.out.println(JSONObject.getNames(o.getJSONObject("cart_1325036696007"))[1]); System.out.println(o.getJSONObject("cart_1325036696007").names().get(1)); System.out.println(o.length()); //共有几组对象 System.out.println(o.has("cart_1325036696007")); //有无该该值 /* 遍历json中的每一组元素*/ String name = null; JSONObject t_o = null; for(int i=0; i<o.length(); i++){ name = JSONObject.getNames(o)[i]; System.out.println("商品项ID:"+name); t_o = o.getJSONObject(name); for(int j=0; j< t_o.length(); j++){ name = JSONObject.getNames(t_o)[j]; System.out.print(name+":"+t_o.get(name)+" "); } System.out.println(); } }catch(Exception e){ e.printStackTrace(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值