如何从json rest服务器应答中检索字段?

如何从json rest服务器应答中检索字段?

问题描述:

有没有一种简单的方法从json rest web服务答案中恢复字段。 例如,这是一个JSON后一个答案:如何从json rest服务器应答中检索字段?

{ 
     "name": "sam", 
     "city": "SF", 
     "number": "0017100000000" (optional), 
     "message": "xyz has occurred" 
    } 

我想在这个例子中检索名称和城市等 我应该使用正则表达式?

我有点新的这一切,所以不要犹豫,告诉我,如果我的问题是在帮助我虽然:)

+2

像[gson](https://github.com/google/gson)使用json解析器 – ndn

+0

切勿将正则表达式用于可轻松解析的内容。 – Identity1

+0

好的,谢谢!那么就是一个gson解析器! – MultiTask70

条件哑请从下面的代码,以便从获得的值JSON对象。为此,您需要“java-json.jar”。

我已经共享了从json数组获取数据的示例代码。随时提问任何问题。

public static void main(String[] args){ 
    try { 
     //Simple Json Object 
     JSONObject testObj= new JSONObject("{name: sam,city: SF,number:0017100000000,message: xyz has occurred}"); 

     System.out.println("Name in json\t" +testObj.get("name")); 
     System.out.println("City in json\t" +testObj.get("city")); 

     //If you want to get from array 
     JSONObject arrObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}"); 

     List<String> list = new ArrayList<String>(); 
     JSONArray array = arrObj.getJSONArray("interests"); 
     for(int i = 0 ; i < array.length() ; i++){ 
      list.add(array.getJSONObject(i).getString("interestKey")); 
     } 


    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


}