jackson解析的基本使用

jackson是一个用Java编写的,用来处理JSON格式数据的类库,它速度非常快,目前来看使用很广泛,逐渐替代了Gson和json-lib。
这是大神解析效率的测试数据的网站http://wangym.iteye.com/blog/738933

jackson解析的基本使用_第1张图片
20141127152011390.png

最终结果是Jackson > Gson > Json-lib。这也就是为什么要掌握jackson解析的意义了
下面是我练习写的一个demo,其实使用起来和Gson比较类似****
首先建一个单例的类提供ObjectMapper对象,后面很多操作会用到这个对象

import org.codehaus.jackson.map.ObjectMapper;
/** * 只用创建一次ObjectMapper对象就可以了 */
public class JacksonMapper {  
  private static ObjectMapper mapper ; 
   public static ObjectMapper getMapper(){
        if(mapper==null){
            synchronized (JacksonMapper.class){
                if(mapper == null){
                    mapper = new ObjectMapper(); 
               }
            }
        }
        return mapper; 
   }
}

然后创建ProductBean对象
这是我解析用的json字符串

{"productProperty":[{"v":"红色","k":"颜色","id":1},{"v":"L","k":"尺寸","id":2}],"name":"毛衣","price":130.0,"id":1}

 import java.util.List;
public class ProductBean {
    public int id;    public String name;
    public float price;
    public List productProperty;
    public ProductBean() {    }
    public ProductBean(int id, String name, float price, List productProperty) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.productProperty = productProperty;
    }
    @Override
    public String toString() {
        return "ProductBean{" +
                "id=" + id +              
                ", name='" + name + '\'' +
                ", price=" + price +
                ", productProperty=" + productProperty +                '}';
    }
}
//商品属性
public class ProductPropertyBean {
    /**     * id : 1     * k : 颜色     * v : 红色
     */
    public int id;
    public String k;
    public String v;
    public ProductPropertyBean() {    } 
   public ProductPropertyBean(int id, String k, String v) {
        this.id = id;
        this.k = k;
        this.v = v;
    }   
 @Override
    public String toString() {
        return "ProductPropertyBean{" + 
               "id=" + id +
                ", k='" + k + '\'' +
                ", v='" + v + '\'' +                '}';
    }
}

jackson使用和Gson比较类似
传递对应的json字符串,和bean对象的字节码就可以了,
如果是数组就传对应的List的字节码

mMapper.readValue(jsonString, ProductBean.class);

想把bean对象转换成json字符串
同样的如果是List直接传递List对象就可以了

mMapper.writeValueAsString(objectBean);

一般也就这两种用法
还有节点解析要用到JsonNode这个对象,类似map根据key获取对应的value值然后asInt()等对应的数据类型就可以了,如果获取的是对象或数组,那只能先tostring()获取对象的json字符串才能接着解析,也就是要一层一层的解析
(注意:对象或数组用asText()获取的字符串为空,所以必须用tostring())

 JsonNode jsonNode = mMapper.readTree(objectJson); 
 JsonNode name = jsonNode.get("name"); 
 JsonNode price = jsonNode.get("price"); 
 JsonNode id = jsonNode.get("id");
name.asText();

public class MainActivity extends AppCompatActivity {
    private static final String TAG ="MainActivity" ;
    @Bind(R.id.tv_object_tojson) 
   TextView mObjectTvTojson; 
   @Bind(R.id.tv_array_tojson)
    TextView mArrayTvTojson;
    @Bind(R.id.tv_toObject)
    TextView mTvToObject;
    @Bind(R.id.tv_toList) 
   TextView mTvToList;
    @Bind(R.id.activity_main)
    LinearLayout mActivityMain;
    private ObjectMapper mMapper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mMapper = JacksonMapper.getMapper();
        //创建ProductBean对象
        ProductBean productBean = createObject();
        //将对象解析成json字符串
        String objectJson = toJson(productBean);
       // String json = toJson2(productBean);
        mObjectTvTojson.setText("toJson==="+objectJson);
        //将数组转化成json字符串
        ArrayList beanArrayList = new ArrayList<>(); 
       beanArrayList.add(productBean);
        beanArrayList.add(productBean);
        beanArrayList.add(productBean);
        String arrayJson =toJson(beanArrayList);
        mArrayTvTojson.setText("toJson==="+arrayJson);
        //将json字符串解析为bean
        ProductBean bean = toObjectBean(objectJson);
        mTvToObject.setText("toObjectBean==="+bean.toString()); 
       //将json字符串解析为List 
       ArrayList list = toArrayBean(arrayJson);
        mTvToList.setText("toArrayBean==="+list.toString());
        //jackson节点解析 
       jsonNode(objectJson);
    }
    public void jsonNode(String objectJson) { 
       //{"productProperty":[{"v":"红色","k":"颜色","id":1},{"v":"L","k":"尺寸","id":2}],"name":"毛衣","price":130.0,"id":1}
        try { 
           JsonNode jsonNode = mMapper.readTree(objectJson); 
           JsonNode productProperty = jsonNode.get("productProperty");
            JsonNode name = jsonNode.get("name");
            JsonNode price = jsonNode.get("price");
            JsonNode id = jsonNode.get("id");
            String propertyString = productProperty.toString(); 
           //如果要转化成对象的话还得用 ObjectMapper的readValue(), productProperty如果用JsonNode的asText()获取的是空 
           ArrayList productPropertyBeans = mMapper.readValue(propertyString, new ArrayList().getClass());
            Log.d(TAG, "jsonNode:name: "+name.asText()); 
           Log.d(TAG, "jsonNode:id: "+id.asInt());
            Log.d(TAG, "jsonNode: price:"+price.asDouble());
            Log.d(TAG, "jsonNode:
 productPropertyBeans"+productPropertyBeans.toString());
        } catch (IOException e) { 
           e.printStackTrace();
            Log.d(TAG, "jsonNode: "+e.toString());
        } 
   }
    public ProductBean createObject(){ 
       //创建ProductBean对象
        ProductPropertyBean color = new ProductPropertyBean(1,"颜色","红色"); 
       ProductPropertyBean size = new ProductPropertyBean(2,"尺寸","L"); 
       ArrayList productPropertyBeen = new ArrayList<>();  
      productPropertyBeen.add(color);        productPropertyBeen.add(size);
        ProductBean productBean = new ProductBean(1,"毛衣",130,productPropertyBeen);
        return productBean;
    }
    public String toJson(Object o){
        String s;
        try { 
           //将对象解析成json字符串
          s = mMapper.writeValueAsString(o);
        } catch (IOException e) {
            e.printStackTrace();
            s = e.toString(); 
       } 
       Log.i(TAG, "getJson: "+s); 
       return s;
    }
    public String toJson2(Object o){ 
       String s;
        try {
            //将对象解析成json字符串 
           StringWriter stringWriter = new StringWriter();
            JsonFactory jsonFactory = mMapper.getJsonFactory(); 
           JsonGenerator jgen = jsonFactory.createJsonGenerator(stringWriter); 
           mMapper.writeValue(jgen,o);
            jgen.flush();
            jgen.close();
            s = stringWriter.toString();
            stringWriter.close();
        } catch (IOException e) { 
           e.printStackTrace();
            s = e.toString();
        }
        Log.i(TAG, "getJson: "+s);
        return s; 
   }
    public ProductBean toObjectBean(String json){
        ProductBean productBean = null;
        try {
          productBean = mMapper.readValue(json, ProductBean.class); 
       } catch (IOException e) { 
           e.printStackTrace(); 
       } 
       return productBean;
    }
    public ArrayList toArrayBean(String json){
       ArrayList list = null; 
       try {
            list = mMapper.readValue(json, new ArrayList().getClass());
        } catch (IOException e) { 
           e.printStackTrace();
        } 
       return list;
    }
}

练习demo的下载https://github.com/starrysky0/jacksondemo
初次尝试写这些东西,主要是总结一下自己的学习情况,如果有什么错误或不足,真诚的希望大神们能指出来

你可能感兴趣的:(jackson解析的基本使用)