JSON

Java中字符串与json间的相互转换教程

字号+ 作者:H5之家 来源:H5之家 2017-06-08 09:13 我要评论( )

Java中字符串与json间的相互转换教程

先给出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:1
userId is:112
element 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

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

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: 1
userId: 112
123,haha
456,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, bean.get("boolean") );
2)JSONObject to JavaBean
JSONLIB在转换的时候会自动查找关系,比如子类和父类
例如JSON数据源
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.toBean()方法的三个参数分别表示数据源对应的JSON对象,转化后的对象ShopList和数据源map。
这种方法和动态转换的区别在于,动态转换仅仅只是转为Object,而静态转换是转换为已经定义过的实体类,会自动映射。JSONObject.toBean()的参数介绍。

Tags:java

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • json result

    json result

    2017-06-08 10:00

  • com.alibaba.fastjson.JSONObject学习

    com.alibaba.fastjson.JSONObject学习

    2017-06-07 11:03

  • JSON学习---ISuperObject接口的简单实用

    JSON学习---ISuperObject接口的简单实用

    2017-06-07 10:19

  • 【图】怎样学习Web开发【权威发布】,json格式

    【图】怎样学习Web开发【权威发布】,json格式

    2017-06-07 10:00

网友点评
/