java与json互转

来源:互联网 发布:2016网络机顶盒排名榜 编辑:程序博客网 时间:2024/04/30 00:17

1.简单的解析json字符串

首先将json字符串转换为json对象,然后再解析json对象,过程如下。
JSONObject jsonObject = JSONObject.fromObject(jsonStr);

[java] view plaincopy
  1. <pre></pre><span style="white-space:pre"></span>  
  2. <pre></pre>  
 根据json中的键得到它的值
String name = jsonObject.getString("name");
int num = jsonObject.getInt("num");
String sex = jsonObject.getString("sex");
int age = jsonObject.getInt("age");

2.将json字符串转换为java对象

同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所示。
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
将json对象转换为java对象
Person jb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象

3.将java对象转换为json字符串

先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
0 0