JSONObject 解析json
来源:互联网 发布:郑州大学网络自助平台 编辑:程序博客网 时间:2024/05/21 09:43
String message = new String(delivery.getBody());//得到交付的消息System.out.println(" [x] 订单 '" + message + "'");JSONObject jsonObject = JSONObject.fromObject(message);Map<String,Object> mapJson = JSONObject.fromObject(jsonObject);
这几天一直在做Java解析Json数据的一个项目,因为初识json,所以很多东西都是有着懵懂的认识。这里写下我解析时遇到的问题和收获。
我解析json时用到的是json-lib包。下载地址:http://json-lib.sourceforge.net。用这个包时,还要用到其他几个支持包:commons-lang.jar、commons-logging.jar,commons-beanutils.jar、xom-1.0-2005-01-05.jar、ezmorph-1.0.1.jar,以上包都可在http://json-lib.sourceforge.net下载。
先给出2个简单的例子。 1.java2json
样例:
public class testJson{
public static void main(String[] args) { String json = "{\"name\":\"reiz\"}"; JSONObject jsonObj = JSONObject.fromObject(json); String name = jsonObj.getString("name"); jsonObj.put("initial", name.substring(0, 1).toUpperCase());
String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" }; jsonObj.put("likes", likes);
Map<String, String> ingredients = new HashMap<String, String>(); ingredients.put("apples", "3kg"); ingredients.put("sugar", "1kg"); ingredients.put("pastry", "2.4kg"); ingredients.put("bestEaten", "outdoors"); jsonObj.put("ingredients",ingredients); System.out.println(jsonObj); } }
输出结果:
{"name":"reiz","initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"}}
java2json的资料网上很多,此不具体研究。
2.javafromjson
例子:
public class testJson{
public static void main(String[] args) { String json = "{x:'1',y:'2',userId:'112',element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}"; JSONObject obj = JSONObject.fromObject(json); String x = obj.getString("x"); String userid = obj.getString("userId"); System.out.println("x is:" + x); System.out.println("userId is:" + userid); // 数组array结果:[{"id":"123","name":"haha"},{"id":"456","name":"hehe"}] JSONArray jsonArray = obj.getJSONArray("element"); for (int i = 0; i < jsonArray.size(); i++) { System.out.println("element " + i + " :" + jsonArray.get(i)); } }} 输出:
x is:1userId is:112element 0 :{"id":"123","name":"haha"}element 1 :{"id":"456","name":"hehe"}
从上例可以看出,若取某一数组,可用json.get(i)取出。若想继续取出数组中第i个元素内的某一个值,如取出数组第一个元素中id的值,可用(JSONObject)json.get(0).getInt("id")取出,为了看出细节,我们设取第二个元素中name的值,代码如下:
JSONObject obj2 = JSONObject.fromObject(array.get(1)); System.out.println(obj2.getString("name"));
输出结果为 hehe
可以看出一般步骤为:将要目标字符串转为JSON对象(JSONObject.fromObject()方法),再根据相应方法取出该对象中需要的值。
如果我们要将json反序列化为javabean呢?
String jsonStr = "{x:1,\"userId\":\"112\",element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}"; Map<String,Class<?>> m = new HashMap<String,Class<?>>(); m.put("x", Integer.class); m.put("userId", String.class); m.put("element",Element.class); Jsontobean myBean = (Jsontobean)JSONObject.toBean( JSONObject.fromObject(jsonStr), Jsontobean.class, m ); System.out.println("x: " + myBean.getX()); System.out.println("userId: " + myBean.getUserId()); for(Element e : myBean.getElement()){ System.out.println(e.getId() +"," + e.getName()); }
public class Jsontobean {
private int x = 1; private String userId = "112"; private List<Element> element; public int getX() { return x; } public void setX(int x) { this.x = x; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public List<Element> getElement() { return element; } public void setElement(List<Element> element) { this.element = element; } }
public class Element {
private int id; private String name; private Element source; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setSource(Element source) { this.source = source; } public Element getSource() { return source; } public String toString(){ return "" + id + "," + name; }} 输出:
x: 1userId: 112123,haha456,hehe
-------
附:jsontojava对象
1)JSONObject to DynaBean
所谓动态bean即是java运行的时候根据情况创建的,而不是程序员已经写好了的Bean。JsonLib会自动根据Json格式数据创建字段,然后创建一个包含这些字段的Object。代码片段:
- String
str "{'string':'JSON',= 'integer': ;1, 'double': 2.0, 'boolean': true}" - JSONObject
jsonObject = (JSONObject) JSONSerializer.toJSON( str ); - DynaBean
bean = (DynaBean) JSONSerializer.toJava( jsonObject ); - assertEquals(
"JSON", bean.get( "string")); - assertEquals(
new Integer( 1),bean.get( "integer")); - assertEquals(
new Double( 2.0),bean.get( "double")); - assertEquals(
Boolean.TRUE, "boolean")bean.get( ); 2)JSONObject to JavaBean
JSONLIB在转换的时候会自动查找关系,比如子类和父类例如JSON数据源
JSONObject.toBean()方法的三个参数分别表示数据源对应的JSON对象,转化后的对象ShopList和数据源map。这种方法和动态转换的区别在于,动态转换仅仅只是转为Object,而静态转换是转换为已经定义过的实体类,会自动映射。JSONObject.toBean()的参数介绍。 String s = "{'shopList':[{name:'重量',property:'p1'},{name:'尺寸',property:'p2'}, {name:'显卡 类型',property:'p3'},{name:'硬盘容量',property:'p4'},{name:'处理器 ',property:'p5'},{name:'内存',property:'p6'},{name:'型号',property:'p7'}, {name:'货号',property:'p8'},{name:'品牌',property:'p9'}]}"; 存入Map map.put("shopList", Shop.class); ShopList shopList = (ShopList) JSONObject.toBean(JSONObject.fromObject(s), ShopList.class, map);
这里,衷心谢谢各位给予我的帮助。
- JSONObject 解析json
- JsonObject 解析 json
- JSONObject/JSONArray解析json
- 解析JSON-JSONObject/GSON
- JSONObject 解析json用法
- 关于JSONObject解析json
- android json解析-JSONObject
- 利用JsonObject解析Json数据
- JSONObject 解析json的步骤
- JSONObject解析json字符串实现
- JSONObject解析Json串(Android)
- JSONObject使用方法详解json解析
- JSONObject类之解析json
- 关于Json解析(org.json.JSONObject)
- JSON与JSONObject解析json数据
- JSON解析 Gson解析方式 JSONObject JSONArray
- android中用jsonObject解析json数据
- JSONObject与JSONArray解析Json数据例子
- NodeJs session中间件 及应用(简单的登录与登出)
- 淘宝穿越。。。@^@
- ehcache,redis和memcache总结
- 真机运行程序Xcode提示The identity used to sign the executable is no longer valid
- 画表格
- JSONObject 解析json
- 高仿微信朋友圈
- [DeepLearning] 深度学习框架Caffe初体验之病斑检测
- 在ftp中填充数据模型
- ros_opencv_按下键p从kinect获取一张一定大小的图片并处理
- 通俗易懂的正则表达式
- 关闭Eclipse按空格和等号键自动补全内容
- lua基本实验
- sql基础03—数据类型