首页 > 代码库 > java代码解析json对象获取json对象属性值

java代码解析json对象获取json对象属性值

说明:解析JSON需要用到 org.json.jar 架包,下载地址:http://download.csdn.net/detail/wtingting5211314/7641749

 

代码如下:

 

package com.ultrapower.syn.webservice.test;

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

public class TestJson {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  String JsonStr = "{data:["
            +"{id: ‘1‘, code: ‘app1‘, name: ‘app1‘, classifierId: ‘Root‘, alterationType: ‘‘, parentId: ‘#‘, attributes: {} },"
            +"{id: ‘2‘, code: ‘app1_db1‘, name: ‘xx‘, classifierId: ‘Catalog‘, alterationType: ‘‘, parentId: ‘1‘, attributes: {}},"
            +"{id: ‘3‘, code: ‘edw‘, name: ‘xx‘, classifierId: ‘Schema‘, alterationType: ‘‘, parentId: ‘2‘, attributes: {}},"
            +"{id: ‘4‘, code: ‘Table1‘, name: ‘表1‘, classifierId: ‘Table‘, alterationType: ‘‘, parentId: ‘3‘, attributes: {}},"
            +"{id: ‘5‘, code: ‘Column1‘, name: ‘字段1‘, classifierId: ‘Column‘, alterationType: ‘delete‘, parentId: ‘4‘, attributes: {length: 20, dataType: ‘varchar‘}},"
            +"{id: ‘6‘, code: ‘Column2‘, name: ‘字段2‘, classifierId: ‘Column‘, alterationType: ‘add‘, parentId: ‘4‘, attributes: {length: 20, dataType: ‘varchar‘}}"
            +"]}";
  
  
  try {
   parseJsonToBeanInfo(JsonStr);
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 public static void parseJsonToBeanInfo(String JsonInfo) throws Exception {

  if(!"".equals(JsonInfo)&&JsonInfo!=null){
   
   //先把String 形式的 JSON 转换位 JSON 对象
   JSONObject json = new JSONObject(JsonInfo); 
   //得到 JSON 属性对象列表
   JSONArray jsonArray =json.getJSONArray("data");
   //遍历,得到属性值
   for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jo = jsonArray.getJSONObject(i);
    String id = jo.getString("id");
    String name = jo.getString("name");
    String parentId = jo.getString("parentId");
    String alterationType = jo.getString("alterationType");

    System.out.print("id is:"+id);
    System.out.print(" name is:"+name);
    System.out.print(" parentId is:"+parentId);
    System.out.println(" alterationType is:"+alterationType);
   } 
  } 
 }
}

 

运行结果如下:

id is:1 name is:app1 parentId is:# alterationType is:
id is:2 name is:xx parentId is:1 alterationType is:
id is:3 name is:xx parentId is:2 alterationType is:
id is:4 name is:表1 parentId is:3 alterationType is:
id is:5 name is:字段1 parentId is:4 alterationType is:delete
id is:6 name is:字段2 parentId is:4 alterationType is:add

 

java代码解析json对象获取json对象属性值