- import com.alibaba.fastjson.JSONObject;
-
-
- /**
- * Created by wangzhenfei on 14-4-15.
- */
- public class FastJsonTest {
- public static void main(String[] args){
- String jsonStr = "{\"JACKIE_ZHANG\":\"張學友\",\"ANDY_LAU\":\"劉德華\",\"LIMING\":\"黎明\",\"Aaron_Kwok\":\"郭富城\"}" ;
-
-
- //做5次測試
- for(int i=0,j=5;i<j;i++)
- {
- JSONObject jsonObject = JSONObject.parseObject(jsonStr) ;
- for(java.util.Map.Entry<String,Object> entry:jsonObject.entrySet()){
- System.out.print(entry.getKey()+"-"+entry.getValue()+"\t");
- }
- System.out.println();//用來換行
- }
- }
- }
運行結果:
- LIMING-黎明 Aaron_Kwok-郭富城JACKIE_ZHANG-張學友ANDY_LAU-劉德華
- Aaron_Kwok-郭富城 ANDY_LAU-劉德華LIMING-黎明JACKIE_ZHANG-張學友
- Aaron_Kwok-郭富城 JACKIE_ZHANG-張學友ANDY_LAU-劉德華LIMING-黎明
- LIMING-黎明 ANDY_LAU-劉德華JACKIE_ZHANG-張學友Aaron_Kwok-郭富城
- JACKIE_ZHANG-張學友 LIMING-黎明ANDY_LAU-劉德華Aaron_Kwok-郭富城
解決辦法:定義為JSONArray,代碼如下:
- import com.alibaba.fastjson.JSONArray;
-
- /**
- * Created by wangzhenfei on 14-4-15.
- */
- public class FastJsonTest {
- public static void main(String[] args){
- String jsonStr = "[{\"JACKIE_ZHANG\":\"張學友\"},{\"ANDY_LAU\":\"劉德華\"},{\"LIMING\":\"黎明\"},{\"Aaron_Kwok\":\"郭富城\"}]" ;
- //做5次測試
- for(int i=0,j=5;i<j;i++)
- {
- JSONArray jsonArray = JSONArray.parseArray(jsonStr);
-
- for(int k=0;k<jsonArray.size();k++){
- System.out.print(jsonArray.get(k) + "\t");
- }
- System.out.println();//用來換行
- }
- }
- }
運行結果為:
- {"JACKIE_ZHANG":"張學友"} {"ANDY_LAU":"劉德華"}{"LIMING":"黎明"}{"Aaron_Kwok":"郭富城"}
- {"JACKIE_ZHANG":"張學友"} {"ANDY_LAU":"劉德華"}{"LIMING":"黎明"}{"Aaron_Kwok":"郭富城"}
- {"JACKIE_ZHANG":"張學友"} {"ANDY_LAU":"劉德華"}{"LIMING":"黎明"}{"Aaron_Kwok":"郭富城"}
- {"JACKIE_ZHANG":"張學友"} {"ANDY_LAU":"劉德華"}{"LIMING":"黎明"}{"Aaron_Kwok":"郭富城"}
- {"JACKIE_ZHANG":"張學友"} {"ANDY_LAU":"劉德華"}{"LIMING":"黎明"}{"Aaron_Kwok":"郭富城"}
如果就想要定義為JSONObject,而不是JSONArray,可以選用其他JSON解析器,個人推薦使用google的gson,文檔明顯比fastjson好很多(從這里可以看出阿里巴巴和谷歌的差距):
- import com.google.gson.JsonElement;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
-
- /**
- * Created by wangzhenfei on 14-4-15.
- */
- public class FastJsonTest {
- public static void main(String[] args){
- String jsonStr = "{\"JACKIE_ZHANG\":\"張學友\",\"ANDY_LAU\":\"劉德華\",\"LIMING\":\"黎明\",\"Aaron_Kwok\":\"郭富城\"}" ;
- //做5次測試
- for(int i=0,j=5;i<j;i++)
- {
- JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonStr);
- for(java.util.Map.Entry<String,JsonElement> entry:jsonObject.entrySet()){
- System.out.print(entry.getKey()+"-"+entry.getValue()+"\t");
- }
- System.out.println();//用來換行
- }
- }
- }
運行結果:
- JACKIE_ZHANG-"張學友" ANDY_LAU-"劉德華" LIMING-"黎明" Aaron_Kwok-"郭富城"
- JACKIE_ZHANG-"張學友" ANDY_LAU-"劉德華" LIMING-"黎明" Aaron_Kwok-"郭富城"
- JACKIE_ZHANG-"張學友" ANDY_LAU-"劉德華" LIMING-"黎明" Aaron_Kwok-"郭富城"
- JACKIE_ZHANG-"張學友" ANDY_LAU-"劉德華" LIMING-"黎明" Aaron_Kwok-"郭富城"
- JACKIE_ZHANG-"張學友" ANDY_LAU-"劉德華" LIMING-"黎明" Aaron_Kwok-"郭富城"