Java中Json转string方法
Java利用Json-lib包进行json对象转换成string
JSONArray转换string方法实例
public static void main(String[] args) throws JSONException { //创建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 { String id; String name; int age; Book book; }
public class Book { String id; String name; }
public class Json { public static void main(String[] args) { 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); } }
运行结果:
{"age":0,"book":{"id":"111","name":"语文"},"id":"002","name":"xim"}
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。