1. 程式人生 > >java和js中JSONObject,JSONArray,Map,String之間轉換——持續更新中

java和js中JSONObject,JSONArray,Map,String之間轉換——持續更新中

--------------------------------------------------java中--------------------------------------------------------------

1.String轉JSONObject

(1).

String jsonMessage = "{\"語文\":\"88\",\"數學\":\"78\",\"計算機\":\"99\"}";

JSONObject  myJson = JSONObject.fromObject(jsonMessage);

(2).用阿里巴巴的fastjson的jar包

String str = "{\"baid\":null,\"32d3:\":\"null\",433:\"0x32\",032:\"ju9fw\"}";
com.alibaba.fastjson.JSONObject jm = com.alibaba.fastjson.JSON.parseObject(str);

2.String轉JSONArray

String jsonMessage = "[{'num':'成績', '外語':88, '歷史':65, '地理':99, 'object':{'aaa':'1111','bbb':'2222','cccc':'3333'}}," +
          "{'num':'興趣', '外語':28, '歷史':45, '地理':19, 'object':{'aaa':'11a11','bbb':'2222','cccc':'3333'}}," +
          "{'num':'愛好', '外語':48, '歷史':62, '地理':39, 'object':{'aaa':'11c11','bbb':'2222','cccc':'3333'}}]";
 JSONArray myJsonArray = JSONArray.fromObject(jsonMessage);
 System.out.println(myJsonArray);

3.String轉Map

(1)

String jsonMessage = "{\"語文\":\"88\",\"數學\":\"78\",\"計算機\":\"99\"}";

JSONObject  myJson = JSONObject.fromObject(jsonMessage);

Map m = myJson; 

(2)用阿里巴巴的fastjson的jar包

String str = "{\"baid\":null,\"32d3:\":\"null\",433:\"0x32\",032:\"ju9fw\"}";
Map mapTypes = com.alibaba.fastjson.JSON.parseObject(str);

(3) (需要引入jackjson的core、databind、annotations三個jar包  )

String json = "{\"PayPal key2\":\"PayPal value2\",\"PayPal key1\":\"PayPal value1\",\"PayPal key3\":\"PayPalvalue3\"}";  

ObjectMapper mapper = new ObjectMapper();    
 Map<String,Object> m = mapper.readValue(json, Map.class);  

(4)(特殊格式的String)

String a ="{se=2016, format=xml, at=en co=3}";

a =  a.substring(1, a.length()-1);
Map docType = new HashMap();  
Java.util.StringTokenizer items;  
for(StringTokenizer entrys = new StringTokenizer(a, ", ");entrys.hasMoreTokens();   
docType.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null)){  
     items = new StringTokenizer(entrys.nextToken(), "=");  
   }

4.JSONObject、JSONArray,Map轉String

JSONObject——String:

System.out.println(myJsonObject);//可直接輸出JSONObject的內容

myJsonObject.toString();

阿里巴巴fastjson

String str = JSON.toJSONString(obj,SerializerFeature.BrowserCompatible);

JSONArray——String:

System.out.println(myJsonArray);//可直接輸出myJsonArray的內容

myJsonArray.toString();

Map——String:

System.out.println(map);//可直接輸出map的內容

map.toString();

5.JSONObject轉JSONArray

6.JSONObject轉Map

JSONObject  myJson = JSONObject.fromObject(jsonString);

Map m = myJson; 

7.JSONArray轉JSONObject

  for(int i=0 ; i < myJsonArray.length() ;i++)
   {
    //獲取每一個JsonObject物件
    JSONObject myjObject = myJsonArray.getJSONObject(i);

}

8.JSONArray轉Map

9.Map轉JSONObject

JSONObject json = JSONObject.fromObject( map );   

String jsonString = JSON.toJSONString(map,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty);

JSONObject jm = JSON.parseObject(str);

(此為alibaba的fastjson)

Map轉json格式的String

JSON.toJSONString(map, SerializerFeature.BrowserCompatible).replace("\\\\u", "\\u");

//需要引入alibaba的fastjson包

10.Map轉JSONArray

   JSONArray.fromObject(map);

11.List轉JSONArray
JSONArray jsonArray2 = JSONArray.fromObject( list );    

fastjson:List轉JSONArray

(1)List<Object> list1 = new ArrayList<Object>();
        list1.add("false");
        list1.add(true);
        list1.add(null);
        list1.add(0x13e);
        list1.add(0123);
        JSONArray array1 = JSONArray.parseArray(JSON.toJSONString(list1));

(2)JSONArray jsonArray = new JSONArray(list1) ;

12.JSONArray轉List

List<Map<String,Object>> mapListJson = (List)jsonArray;

public static List<Map<String, Object>> jsonArrayToList(JSONArray ja){  
        return JSONArray.toJavaObject(ja, List.class);  
    } 

fastjson:JSONArray轉List

JSONArray arr = new JSONArray();
        arr.add(0,"13");
        arr.add(1,"jo");
        arr.add(2,"kpo");
        List<String> list = JSONObject.parseArray(array.toJSONString(), String.class);

JSONArray array = new JSONArray();

List<T> list = JSONObject.parseArray(array.toJSONString(), T.class);

13.String轉陣列

String string = "a,b,c";
String [] stringArr= string.split(",");  //注意分隔符是需要轉譯滴...
如果是"abc"這種字串,就直接
String string = "abc" ;
char [] stringArr = string.toCharArray(); //注意返回值是char陣列
如果要返回byte陣列就直接使用getBytes方法就ok了~~
String string = "abc" ;
byte [] stringArr = string.getBytes();

String轉List

String str = "";

List<T> list = JSONObject.parseArray(str, T.class);

陣列轉String

char[] data={a,b,c}; 
String s=new String(data); 

14.java實體類的List轉String

JSON與String關係比較近,而JSON的子類JSONArray又和List關係比較近,故把JSONArray做中介過渡:

import com.alibaba.fastjson.JSONArray;

public String list2str(List<?> list){
JSONArray jsonArray = (JSONArray) JSONArray.toJSON(list);   //List轉JSONArray
System.out.println(jsonArray.toString());
return jsonArray.toJSONString();    //JSONArray比較容易轉String
}

15.Array、List、Set之間轉換

String[] arr = new String[]{"Tom", "Bob", "Jane"};
//Array轉List
List<String> arr2list = Arrays.asList(arr);
//Array轉Set
Set<String> arr2set = new HashSet<String>(Arrays.asList(arr));
//List轉Array
Object[] list2arr = arr2list.toArray();
//List轉Set
Set<String> list2set = new HashSet<>(arr2list);
//Set轉Array
Object[] set2arr = list2set.toArray();
//Set轉List
List<String> set2list = new ArrayList<>(arr2set);
List<String> list = new ArrayList<String>(new HashSet<String>());//

--------------------------------------------js中---------------------------------------

js中自定義的map請參考:http://blog.csdn.net/superit401/article/details/72842469

1.json轉Map(並獲取key和value)

var str = JSON.stringify(json);

 str = '{ "10.10.11.1": { "target_1": "34.2","target_3": "70.83","target_2": "50.51"}}';
var map = eval("("+str+")");

//以下為獲取Map的key-value:
for (var key in map) {  
var a = map[key];
for (var k in a) {  
alert(k+'---'+a[k]);
}   
  }

參考:http://www.bkjia.com/webzh/899371.html

2.Map轉json:

不能直接map轉json:var mjson = JSON.parse(map);

也不能var mjson = $.parseJSON(map);//結果為null

只能分兩步走:

var mstr = JSON.stringify(map);

var jsonstr = JSON.parse(mstr);

(注:有的瀏覽器不支援JSON.parse()方法,使用jQuery.parseJSON()方法時,在瀏覽器支援時會返回執行JSON.parse()方法的結果,否則會返回類似執行eval()方法的結果)

參考:http://www.jb51.net/article/87642.htm

3.json轉String:

JSON.stringify(json);

4.String轉json:

var str = '{ "10.10.11.1": { "target_1": "34.2","target_3": "70.83","target_2": "50.51"}}';

var jsonstr = JSON.parse(str);

5.Map轉String:

var mstr = JSON.stringify(map);

6.String轉Map:

var str = '{ "10.10.11.1": { "target_1": "34.2","target_3": "70.83","target_2": "50.51"}}';
var map = eval("("+str+")");