Java中string字符串转json对象方法
Java利用JSONObject进行string字符串转换成JSON对象
转换实例一
public class StringToJSON {
public static void main(String[] args) throws JSONException{
System.out.println("abc");
//定义JSON字符串
String jsonStr = "{\"id\": 2," +
" \"title\": \"json title\", " +
"\"config\": {" +
"\"width\": 34," +
"\"height\": 35," +
"}, \"data\": [" +
"\"JAVA\", \"JavaScript\", \"PHP\"" +
"]}";
//转换成为JSONObject对象
JSONObject jsonObj = new JSONObject(jsonStr);
//从JSONObject对象中获取数据
JavaBean bean = new JavaBean();
//根据属性名称获取int型数据;
bean.setId(jsonObj.getInt("id"));
//根据属性名获取String数据;
bean.setTitle(jsonObj.getString("title"));
//根据属性名获取JSONObject类
JSONObject config = jsonObj.getJSONObject("config");
bean.setWidth(config.getInt("width"));
bean.setHeight(config.getInt("height"));
//根据属性名获取JSONArray数组
JSONArray data = jsonObj.getJSONArray("data");
for(int index = 0, length = data.length(); index < length; index++) {
}
}
}
转换实例二
public class User {
String id;
String name;
int age;
}
public class Json{
public static void main(String[] args) {
//String 转json
String text ="{'id':'001','name':'jack','age':22}";
JSONObject jo =JSONObject.fromObject(text);
System.out.println(jo.get("id") +"__"+ jo.get("name") +"___" + jo.getInt("age"));
//String 转对象 等于是先转成json然后转对象
String text2="{'id':'002','name':'lion','age':23}";
User u1 = (User)JSONObject.toBean(JSONObject.fromObject(text2), User.class);
System.out.println(u1.getId()+"___"+u1.getName()+"__"+u1.getAge());
//对象转json
User u =new User();
u.setId("003");
u.setAge(25);
u.setName("Tom");
JSONObject jo2 =JSONObject.fromObject(u);
System.out.println(jo2);
System.out.println(jo2.get("name"));
}
}
执行结果:
001__jack___22
002___lion__23
{"age":25,"id":"003","name":"Tom"}
Tom
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。