Java中Json转string方法
Java利用Json-lib包进行json对象转换成string
JSONArray转换string方法实例
public static void main(String[] args) throws JSONException {undefined
//创建JSONObject对象
JSONObject json = new JSONObject();
//向json中添加数据
json.put("username", "wanglihong");
json.put("height", 12.5);
json.put("age", 24);
//创建JSONArray数组,并将json添加到数组
JSONArray array = new JSONArray();
array.put(json);
//转换为字符串
String jsonStr = array.toString()
System.out.println(jsonStr);
}
输出结果:
[{"username":"wanglihong","height":12.5,"age":24}]
JSONObject转换string方法实例
public class User {undefined
String id;
String name;
int age;
Book book;
}
public class Book {undefined
String id;
String name;
}
public class Json {undefined
public static void main(String[] args) {undefined
Book book = new Book();
book.setId("111");
book.setName("语文");
User u = new User();
u.setId("002");
u.setName("xim");
u.setBook(book);
JSONObject jo = JSONObject.fromObject(u);
System.out.println(jo);
}
}