java生成json字串的方法

只爭朝夕^ω^)↗發表於2018-08-28

例1:將map物件新增一次元素(包括字串對、陣列),轉換成json物件一次。

package com.json;

//這是使用org.json的程式:
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class jsontest {

public static void main(String[] args) throws JSONException {
String json = "{'name':'reiz'}";
JSONObject jsonObj = new JSONObject(json);
String name = jsonObj.getString("name");

System.out.println(jsonObj);

jsonObj.put("initial", name.substring(0, 1).toUpperCase());

String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
jsonObj.put("likes", likes);

System.out.println(jsonObj);

Map <String, String> ingredients = new HashMap <String, String>();
ingredients.put("apples", "3kg");
ingredients.put("sugar", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
jsonObj.put("ingredients", ingredients);
System.out.println(jsonObj);


}
}

執行結果:

{"name":"reiz"}
{"initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"name":"reiz"}
{"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"},"initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"name":"reiz"}

其次,例2:list轉換成json的三種引數形式。例3:json轉換成list和map。等問題
可以轉到該部落格進行觀看 https://www.cnblogs.com/zhujiabin/p/5498555.html

相關文章