0

How to get the particular data object from the JSON data from the given JSON data:

{
    "customer":{
        "id":1117198024800,
        "email":"[email protected]",
        "accepts_marketing":false
    }
}

I need to parse ID from the above data, Can anyone help me please. Thanks in advance!!!

4
  • so how your getting this json can you tell me ? Commented Feb 6, 2019 at 13:26
  • can you please share your code? Commented Feb 6, 2019 at 13:26
  • @Ashish JSONObject responceObj = new JSONObject(data); //getting customer id from JSON data JSONObject childObj = responceObj.getJSONObject("customer"); for(int k=0;k<childObj.length();k++){ //long id = childObj.getJSONObject(String.valueOf(0)).getLong("id"); long id = childObj.getJSONObject(String.valueOf(0)).optLong("id"); } Commented Feb 6, 2019 at 13:28
  • see here geeksforgeeks.org/parse-json-java Commented Feb 6, 2019 at 13:36

3 Answers 3

1

If you will use it as string:

JSONObject reader = new JSONObject(data);
JSONObject customer = reader.getJSONObject("customer");
String id = (String) customer.getString("id");
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not getting the response of the Id since it is long type, tell me how it was done by you
JSONObject reader = new JSONObject(data); JSONObject customer = reader.getJSONObject("customer"); long id = customer.getLong("id");
1

Use this

  JSONObject responceObj = new JSONObject(data);
     JSONObject customer= response.getJSONObject("customer");
           String id= customer.getString("id");
           String email= customer.getString("email"); 
           String accepts_marketing= customer.getString("accepts_marketing"); 

1 Comment

I'm not getting the response of the Id since it is long type, tell me how it was done by you
0

add to app/build.gradle:

dependencies {
...
implementation "com.google.code.gson:gson:2.8.1"
  }

In code:

     String string = "{
            \"customer\":{
                \"id\":1117198024800,
                \"email\":\"[email protected]\",
                \"accepts_marketing\":false
            }
        }";
        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<HashMap<String,Customer>>() {}.getType();
        HashMap<String, Customer> hashMap = new Gson().fromJson(string, type).
        Customer customer = hashMap.get("customer");

Customer.java class:

 public class Customer{
    Long id;
    String email;
    Boolean acceptsMarketing;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.