将json字符串转换为java中的数组

时间:2014-01-06 12:22:14

标签: java json

我对java不太熟悉。但我知道在php中我们可以使用json_decode函数。 java中是否有任何特定的函数将下面的字符串解码为数组?

[ {
  "type" : "panaroma",
  "image" : "http://test.com/images/aneesh/Desktop/19_september/pano-1.png",
  "location" : "{{487,393},{197,235}}",
  "trigger" : "{{487,393},{197,235}}",
  "orientation" : "portrait",      
} ]

1 个答案:

答案 0 :(得分:0)

看看这个:http://www.tutorialspoint.com/json/json_java_example.htm
有些人喜欢这样:

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

class JsonDecodeDemo 
{
   public static void main(String[] args) 
   {
      JSONParser parser=new JSONParser();
      String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
      try{
         Object obj = parser.parse(s);
         JSONArray array = (JSONArray)obj;
         System.out.println("The 2nd element of array");
         System.out.println(array.get(1));
         System.out.println();

         JSONObject obj2 = (JSONObject)array.get(1);
         System.out.println("Field \"1\"");
         System.out.println(obj2.get("1"));    

         s = "{}";
         obj = parser.parse(s);
         System.out.println(obj);

         s= "[5,]";
         obj = parser.parse(s);
         System.out.println(obj);

         s= "[5,,2]";
         obj = parser.parse(s);
         System.out.println(obj);
      }catch(ParseException pe){
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}