skip to Main Content

I got this json object data which is

{
  "data": {
    "id": 2,
    "email": "[email protected]",
    "first_name": "Janet",
    "last_name": "Weaver",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"
  },
  "ad": {
    "company": "StatusCode Weekly",
    "url": "http://statuscode.org/",
    "text": "A weekly newsletter  focusing on software development, infrastructure, the server, performance, and the stack end of things."
  }
}

I want to parse json which i want to print output email in object…I use org.simple.json library .

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("curl -s -S https://reqres.in/api/users/2");

BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));

String result = br.readLine();
Object obj=JSONValue.parse(result);

How do I println email data via data -> email

5

Answers


  1. Download dependency https://mvnrepository.com/artifact/org.json/json/20180813
    and Use below code –

    import org.json.JSONObject;
    public class TestJson {
        public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("curl -s -S https://reqres.in/api/users/2");
        BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String result = br.readLine();
        JSONObject obj = new JSONObject(result);
        String email = obj.getJSONObject("data").getString("email");
        System.out.println(email);
        }
    }
    
    Login or Signup to reply.
  2. You can just cast the value to JSONObject and use JSONObject API further for printing

        JSONObject jsonObject = (JSONObject) JSONValue.parse(result);
        JSONObject data = (JSONObject) jsonObject.get("data");
        String email= (String) data.get("email");
        System.out.println("Email= " + email);
    
    Login or Signup to reply.
  3. According the java doc, JSONValue.parse returns

    Instance of the following: org.json.simple.JSONObject, org.json.simple.JSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null

    In your case it should be a JSONObject,so you can cast it to a JSONObject and use method in JSONObject to retrive email.

    Object obj=JSONValue.parse(result);
    JSONObject jsonObject=(JSONObject)obj;
    JSONObject data=(JSONObject)jsonObject.get("data");
    String email= (String)data.get("email");
    

    In recent version JSONObject has been deprecated, use JsonObject instead, which don’t bother using so many casting.

    Login or Signup to reply.
  4. ObjectMapper can also be used:

    use the pom to download the dependency.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.1.2</version>
     </dependency>
    

    Code:-

    import com.fasterxml.jackson.databind.ObjectMapper;
    
        public class HelloWorld{
        
             public static void main(String []args){
                String dataJson = "{"data":{"id":2,"email":"[email protected]","first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},"ad":{"company":"StatusCode Weekly","url":"http://statuscode.org/","text":"A weekly newslettern" + 
                        "focusing on software development, infrastructure, the server,n" + 
                        "performance, and the stack end of things."}}";
                
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    A a = objectMapper.readValue(dataJson, A.class);
        
                    System.out.println("email  = " + a.data.email);
                } catch (Exception e) {
                    e.printStackTrace();
                }
             }
        }
        
        
        class A{
            B data;
        }
        class B{
            int id;
            String email;
            String first_name;
            String last_name;
            String avatar;
            String ad;
            String url;
            String text;
            
        }
    
    Login or Signup to reply.
  5. I think that in general case you have to use some JSON parser framework like Jackson. But in case you have to find only one value and do not care about json validation or other aspects, then you could use simple RegExp:

    public static String getEmail(String json) {
        Pattern pattern = Pattern.compile(""email"\s*:\s*"(?<email>[^"]+)"");
        Matcher matcher = pattern.matcher(json);
        return matcher.find() ? matcher.group("email") : null;
    }
    

    or event simplier str.indexOf():

    public static String getEmail(String json) {
        int pos = json.indexOf(""email"");
        pos = pos == -1 ? pos : json.indexOf('"', pos + 7);
        return pos == -1 ? null : json.substring(pos + 1, json.indexOf('"', pos + 1));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search