詳解java生成json字符串的辦法。本站提示廣大學習愛好者:(詳解java生成json字符串的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解java生成json字符串的辦法正文
例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"}
(需求用到的包可在官網下載:http://www.json.org/java/index.html)
例2:list轉換成json的三種參數方式。
import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class listToJson { public static void main(String[] args) { boolean[] boolArray = new boolean[]{true,false,true}; JSONArray jsonArray1 = JSONArray.fromObject( boolArray ); System.out.println( jsonArray1 ); // prints [true,false,true] List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); System.out.println( jsonArray2 ); // prints ["first","second"] JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" ); System.out.println( jsonArray3 ); // prints ["json","is","easy"] } }
運轉後果:
[true,false,true] ["first","second"] ["json","is","easy"]
例3:json轉換成list和map。
package com.json; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class jsonToListandMap { public static void main(String[] args) { // TODO Auto-generated method stub String listStr = "[\"apple\",\"orange\"]"; Collection<String> strlist = JSONArray.toCollection(JSONArray.fromObject(listStr)); for (String str : strlist) { System.out.println(str); } String mapStr = "{\"age\":30,\"name\":\"Michael\",\"baby\":[\"Lucy\",\"Lily\"]}"; Map<String, Object> map = (Map) JSONObject.toBean(JSONObject .fromObject(mapStr), Map.class); for (Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } }
運轉後果:
apple
orange
name Michael
age 30
baby [Lucy, Lily]
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。