Java下json的解析方法-----GSON与JSONObject

GSON:

         Gson是google开发的json格式解析包,其特点是在解析json之前必须知道所传输的json数据格式,并定义一系列层次结构与json层次结构相同的类。换句话说,如果传输的json结构为:

{  
    "name":"relin",  
    "sex":"male",  
    "age":26  
}  

那么,就必须预先定义一个成员变量名字与json中属性名字完全相同的类:

class Person {  
    public String name;  
    public String sex;  
    public int age;  
}  

Gson解析json有三个特点:

  •       如果预先定义的类中不包含json中的某个属性,则该属性就不会被解析出来,但是其他成员仍然能正常解析
  •       命名必须完全相同,否则不会被正常解析
  •       类的成员变量可以是public,也可以是private

让我们来看两个简单的解析与反解析过程:

1. 定义类:

package com.relin.gson.data;  
  
public class Person {  
    private String name;      
    private int age;      
    private int sex;  
    /**     * @return the name     */      
    public String getName() {  
        return name+"*****";      
    }      
      
    /**     * @param name the name to set     */     
    public void setName(String name) {    
        this.name = name;    
    }      
      
    /**     * @return the age     */      
    public int getAge() {          
        return age;      
    }      
      
    /**     * @param age the age to set     */      
    public void setAge(int age) {   
        this.age = age;      
        }          
      
    @Override      
    public String toString() {  
        return name + ":" + age;    
    }  
}  

2. String to json:

private static boolean StringToJson(){  
    try{  
        String str = "{\"name\":\"name0\",\"age\":0}";  
        Gson gson = new Gson();  
        Person person= gson.fromJson(str, Person.class);  
        System.out.println(person);  
    } catch (Exception e){  
        return false;  
    }  
    return true;  
}

3. Json to String:

private static boolean JsonToString(){  
    try{  
        Gson gson = new Gson();  
        ArrayList<Person> persons = new ArrayList<Person>();  
        for (int i = 0; i < 10; i++) {  
            Person p = new Person();       
            p.setName("name" + i);       
            p.setAge(i * 5);       
            persons.add(p);  
        }  
        String str = gson.toJson(persons);  
        System.out.println(str);  
    } catch (Exception e){  
        return false;  
    }  
    return true;  
}  

4. 调用可以如下所示:

package com.relin.gson;  
  
import java.util.ArrayList;  
  
import com.google.gson.Gson;  
import com.relin.gson.data.Person;  
import com.relin.gson.data.UrlResponse;  
  
public class Example {  
    private static boolean JsonToString(){  
        try{  
            Gson gson = new Gson();  
            ArrayList<Person> persons = new ArrayList<Person>();  
            for (int i = 0; i < 10; i++) {  
                Person p = new Person();       
                p.setName("name" + i);       
                p.setAge(i * 5);       
                persons.add(p);  
            }  
            String str = gson.toJson(persons);  
            System.out.println(str);  
        } catch (Exception e){  
            return false;  
        }  
        return true;  
    }  

    private static boolean StringToJson(){  
        try{  
            String str = "{\"name\":\"name0\",\"age\":0}";  
            Gson gson = new Gson();  
            Person person= gson.fromJson(str, Person.class);  
            System.out.println(person);  
        } catch (Exception e){  
            return false;  
        }  
        return true;  
    }

    public static void main(String agrs[]){
        StringToJson();  
        JsonToString()
    }
}

 

JSONObject 是一个final类,继承了Object,实现了JSON接口

构造方法如下:

JSONObject();创建一个空的JSONObject对象

JSONObject(boolean isNull);创建一个是否为空的JSONObject对象

普通方法如下:

fromBean(Object bean);静态方法,通过一个pojo对象创建一个JSONObject对象

fromJSONObject(JSONObject object);静态方法,通过另外一个JSONObject对象构造一个JSONObject对象

fromJSONString(JSONString string);静态方法,通过一个JSONString创建一个JSONObject对象

toString();把JSONObject对象转换为json格式的字符串

iterator();返回一个Iterator对象来遍历元素

其中包含有个主要的类:

1.JSONObject相当与json中的字典类型

2.JSONArray相当与json中的数组类型

基本用法如下:

import net.sf.json.JSONArray;   
import net.sf.json.JSONObject;   
  
public class JSONObjectSample {   
      
    //创建JSONObject对象   
    private static JSONObject createJSONObject(){   
        JSONObject jsonObject = new JSONObject();   
        jsonObject.put("name", "kevin");   
        jsonObject.put("Max.score", new Integer(100));   
        jsonObject.put("Min.score", new Integer(50));   
        jsonObject.put("nickname", "picglet");   
        return jsonObject;   
    }   
    public static void main(String[] args) {   
        JSONObject jsonObject = JSONObjectSample.createJSONObject();   
        //输出jsonobject对象   
        System.out.println("jsonObject==>"+jsonObject);   
           
        //判读输出对象的类型   
        boolean isArray = jsonObject.isArray();   
        boolean isEmpty = jsonObject.isEmpty();   
        boolean isNullObject = jsonObject.isNullObject();   
        System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);   
           
        //添加属性   
        jsonObject.element("address", "swap lake");   
        System.out.println("添加属性后的对象==>"+jsonObject);   
           
        //返回一个JSONArray对象   
        JSONArray jsonArray = new JSONArray();   
        jsonArray.add(0, "this is a jsonArray value");   
        jsonArray.add(1,"another jsonArray value");   
        jsonObject.element("jsonArray", jsonArray);   
        JSONArray array = jsonObject.getJSONArray("jsonArray");   
        System.out.println("返回一个JSONArray对象:"+array);   
        //添加JSONArray后的值   
        //{"name":"kevin","Max.score":100,"Min.score":50,"nickname":"picglet","address":"swap lake",   
        //"jsonArray":["this is a jsonArray value","another jsonArray value"]}   
        System.out.println(jsonObject);   
           
        //根据key返回一个字符串   
        String jsonString = jsonObject.getString("name");   
        System.out.println("jsonString==>"+jsonString); 
        
        //解析一个json对象(可以解析不同类型的数据)
        jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");
        System.out.println(jsonObject);
        //{"d":"test","e":true,"b":1.1,"c":1,"a":1}
        System.out.println(jsonObject.getInt("a"));
        System.out.println(jsonObject.getDouble("b"));
        System.out.println(jsonObject.getLong("c"));
        System.out.println(jsonObject.getString("d"));
        System.out.println(jsonObject.getBoolean("e"));
    }   
    
    public static JSONObject getJSONObject(String str) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(str);
        } catch (JSONException e) {
            e.printStackTrace(System.err);
        }
        return jsonObject;
    }
}  

 

转载于:https://my.oschina.net/u/2331760/blog/1504543

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.LinkedTreeMap.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.class com.google.gson.internal.bind.SqlDateTypeAdapter.class com.google.gson.internal.bind.TimeTypeAdapter.class com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.class com.google.gson.internal.bind.TypeAdapters.class com.google.gson.reflect.TypeToken.class com.google.gson.stream.JsonReader.class com.google.gson.stream.JsonScope.class com.google.gson.stream.JsonToken.class com.google.gson.stream.JsonWriter.class com.google.gson.stream.MalformedJsonException.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值