- 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-"郭富城"