2

Is there a simple way to recover field from a json rest web service answer. For example, this is an answer for a json post:

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

I would like to retrieve name and city for this example, etc. Should I use a regex?

I am a little new to all of this so don't hesitate to tell me if my question is dumb on the condition of helping me though :)

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
MultiTask70
  • 51
  • 1
  • 9

1 Answers1

1

Please find below code in order to get the values from JSONobject.For this you would need "java-json.jar".

I have shared sample code for getting data from json array also.Feel free to ask any questions.

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();
    }


}