尝试了三种,但是其中有一种有坑,如下:
private void createStringJson(){ JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name","张三"); //粉丝是个数组,其实就是嵌套json JSONObject book1 = new JSONObject(); book1.put("bookname","麦田里的守望者"); book1.put("id","1000001"); JSONObject book2= new JSONObject(); book2.put("bookname","月亮与六便士"); book2.put("id","1000002"); //从此处可以看出其实list和json也是互相转换的 List<JSONObject> books= new ArrayList<JSONObject>(); jsonObjects.add(book1); jsonObjects.add(book2); jsonObject.put("books",books); Log.d("aaaaaaaaaaaaaaa",jsonObject+""); } catch (JSONException e) { e.printStackTrace(); } }
上面的jsonObject打印,标签books对应的json是带引号的。
下面的这种方法,标签books对应的json是不带引号的:
//第二种方法,用map方式 private void mapCreateJson(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("name","张三"); Map<String,Object> book1 = new HashMap<String,Object>(); book1.put("bookname","麦田里的守望者"); book1.put("id","1000001"); Map<String,Object> book2 = new HashMap<String,Object>(); book2.put("bookname","月亮与六便士"); book2.put("id","1000002"); List<Map> books = new ArrayList<Map>(); books.add(book1); books.add(book2); map.put("books",books); Log.d("aaaaaaaaaaaaaaa",new JSONObject(map)+""); }
第三种方法,也是不带引号的:
private void beanCreateJson(){ User actor = new User(); actor.setName("张三"); Map<String,Object> book1 = new HashMap<String,Object>(); book1.put("bookname","麦田里的守望者"); book1.put("id","1000001"); Map<String,Object> book2 = new HashMap<String,Object>(); book2.put("bookname","月亮与六便士"); book2.put("id","1000002"); List<Map> books = new ArrayList<Map>(); books.add(book1); books.add(book2); actor.setBooks(books); Log.d("aaaaaaaaaaaaaaa", GsonUtil.beanToString(actor)); }
GsonUtil中beanToString的方法:
import com.google.gson.Gson;
private static Gson gson = new Gson();
public static String beanToString(Object object) { String gsonString = null; if (gson != null) { gsonString = gson.toJson(object); } return gsonString; }