首页 > 编程语言 > 详细

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

时间:2017-02-15 18:16:42      阅读:665      评论:0      收藏:0      [点我收藏+]

说明:解析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对象属性值

原文:http://www.cnblogs.com/pinganjiankang/p/6402572.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!