如何在Java中解码此JSON对象数据

huangapple go评论61阅读模式
英文:

How to decode this json object data in java

问题

{
  "data": {
    "id": 2,
    "email": "janet.weaver@reqres.in",
    "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."
  }
}

要解析 JSON 数据并打印出位于 "data" 下的 "email" 数据,你可以使用 org.simple.json 库:

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

JSONObject jsonObject = (JSONObject) obj;
JSONObject dataObject = (JSONObject) jsonObject.get("data");
String email = (String) dataObject.get("email");

System.out.println(email);
英文:

I got this json object data which is

{
  "data": {
    "id": 2,
    "email": "janet.weaver@reqres.in",
    "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

答案1

得分: 2

你只需要将值转换为 JSONObject,然后进一步使用 JSONObject 的 API 进行打印:

JSONObject jsonObject = (JSONObject) JSONValue.parse(result);
JSONObject data = (JSONObject) jsonObject.get("data");
String email = (String) data.get("email");
System.out.println("Email= " + email);
英文:

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

答案2

得分: 1

根据 Java 文档,JSONValue.parse 返回以下类型的实例:

org.json.simple.JSONObject、org.json.simple.JSONArray、java.lang.String、java.lang.Number、java.lang.Boolean、null

在你的情况下,应该是一个 JSONObject,因此你可以将其转换为 JSONObject 并使用 JSONObject 中的方法来获取电子邮件。

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

在最近的版本中,JSONObject 已被弃用,改用 JsonObject,这样就不需要使用那么多的类型转换了。

英文:

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.

答案3

得分: 0

下载依赖项 https://mvnrepository.com/artifact/org.json/json/20180813
并使用以下代码 -

    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);
        }
    }
英文:

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

答案4

得分: 0

以下是翻译好的内容:

ObjectMapper 也可以被使用

使用 pom 下载依赖项

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

代码

import com.fasterxml.jackson.databind.ObjectMapper;

public class HelloWorld{

    public static void main(String []args){
        String dataJson = "{\"data\":{\"id\":2,\"email\":\"janet.weaver@reqres.in\",\"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\\n\" + 
                    \"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;

}
英文:

ObjectMapper can also be used:

use the pom to download the dependency.

&lt;dependency&gt;
    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
    &lt;version&gt;2.1.2&lt;/version&gt;
 &lt;/dependency&gt;

Code:-

import com.fasterxml.jackson.databind.ObjectMapper;

    public class HelloWorld{
    
         public static void main(String []args){
            String dataJson = &quot;{\&quot;data\&quot;:{\&quot;id\&quot;:2,\&quot;email\&quot;:\&quot;janet.weaver@reqres.in\&quot;,\&quot;first_name\&quot;:\&quot;Janet\&quot;,\&quot;last_name\&quot;:\&quot;Weaver\&quot;,\&quot;avatar\&quot;:\&quot;https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg\&quot;},\&quot;ad\&quot;:{\&quot;company\&quot;:\&quot;StatusCode Weekly\&quot;,\&quot;url\&quot;:\&quot;http://statuscode.org/\&quot;,\&quot;text\&quot;:\&quot;A weekly newsletter\n&quot; + 
    				&quot;focusing on software development, infrastructure, the server,\n&quot; + 
    				&quot;performance, and the stack end of things.\&quot;}}&quot;;
    		
    		ObjectMapper objectMapper = new ObjectMapper();
    		try {
    		    A a = objectMapper.readValue(dataJson, A.class);
    
    		    System.out.println(&quot;email  = &quot; + 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;
    	
    }

答案5

得分: 0

我认为通常情况下,您需要使用一些JSON解析框架,比如Jackson。但是,如果您只需要找到一个值,并且不关心json的验证或其他方面,那么您可以使用简单的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;
}

或者更简单的 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));
}
英文:

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(&quot;\&quot;email\&quot;\\s*:\\s*\&quot;(?&lt;email&gt;[^\&quot;]+)\&quot;&quot;);
    Matcher matcher = pattern.matcher(json);
    return matcher.find() ? matcher.group(&quot;email&quot;) : null;
}

or event simplier str.indexOf():

public static String getEmail(String json) {
    int pos = json.indexOf(&quot;\&quot;email\&quot;&quot;);
    pos = pos == -1 ? pos : json.indexOf(&#39;&quot;&#39;, pos + 7);
    return pos == -1 ? null : json.substring(pos + 1, json.indexOf(&#39;&quot;&#39;, pos + 1));
}

huangapple
  • 本文由 发表于 2020年10月13日 11:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64328157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定