使用 Java 从 JSON 中提取名称/值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22004160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:59:10  来源:igfitidea点击:

Extracting name/value pairs from JSON with Java

javajsonparsing

提问by Mislav Javor

I have this JSON code:

我有这个 JSON 代码:

{
"success": 1,
"item": [
    {
        "itemId": "jogurt123",
        "name": "Jogurt",
        "description": "kajmak",
        "pictureUrl": "https://www.google.hr/images/srpr/logo11w.png",
        "categoryId": "mlijeko"
    }
],
"specs": [
    {
        "specId": "volumen",
        "value": "1",
        "unit": "litra"
    },
    {
        "specId": "mast",
        "value": "50",
        "unit": "%"
    }
]

}

}

I wonder how to extract name/value pairs into Strings using Java. I would like to get the end result:

我想知道如何使用 Java 将名称/值对提取到字符串中。我想得到最终结果:

String name = "Jogurt"
String description = "kajmak"
etc...

I tried using JSONObject to create an object that contains this name/value pairs and I wanted to extract them then but in the following code

我尝试使用 JSONObject 创建一个包含此名称/值对的对象,然后我想提取它们,但在以下代码中

    String getParam(String code, String element){
    try {
        String base = this.getItembyID(code);
        JSONObject product = new JSONObject(base);
        String param = product.getString("name");
        return param;
    } catch (JSONException e) {
        e.printStackTrace();
        return "error";
    }
    }

I get an exception saying that there is not an element "name" in the JSONObject when clearly there is. Any suggestions?

我收到一个异常,说 JSONObject 中没有元素“名称”,但显然存在。有什么建议?

EDIT: The getItembyID method returns the JSON code written above in a string form. JSON code has been validated

编辑:getItembyID 方法以字符串形式返回上面编写的 JSON 代码。JSON 代码已通过验证

采纳答案by Nambi

{ ->JSONObject

{ -> JSONObject

[-> JSONArray

[-> JSONArray

You need to get the jsonObject inside the Jsonarray

您需要在 Jsonarray 中获取 jsonObject

Do like this

这样做

String getParam(String code, String element){
    try {
           String base = this.getItembyID(code);
           JSONObject product = new JSONObject(base);
          JSONArray jarray = product.getJSONArray("item");
         String param =  jarray.getJSONObject(0).getString("name");
  return param;
    } catch (JSONException e) {
        e.printStackTrace();
        return "error";
    }
    }

回答by Sotirios Delimanolis

Assuming baseis the JSON you posted in your question, then your assumptions stated here

假设base是您在问题中发布的 JSON,那么您的假设在此处说明

I get an exception saying that there is not an element "name" in the JSONObject when clearly there is.

我收到一个异常,说 JSONObject 中没有元素“名称”,但显然存在。

are wrong. The JSON object you've shown contains only 3 elements: success, item, and specs. itemis a JSON array with a single element, another JSON object. That JSON object contains a value named name.

错了。还有你的JSON对象仅包含三个元素:successitem,和specsitem是一个带有单个元素的 JSON 数组,另一个 JSON 对象。该 JSON 对象包含一个名为 的值name

You need to get thatJSON object so that you can retrieve thatvalue.

您需要获取JSON 对象,以便您可以检索值。

Or consider using a different JSON parsing library like Hymanson or Gson that mostly does this for you based on some POJO class.

或者考虑使用不同的 JSON 解析库,如 Hymanson 或 Gson,它们主要基于某些 POJO 类为您执行此操作。

回答by ravi.patel

If u have java classes for particular data u are getting in form of json. Then it would be easy to extract data by using Hymanson library. [ Download: http://repo1.maven.org/maven2/com/fasterxml/Hymanson/core/Hymanson-core/2.2.3/Hymanson-core-2.2.3.jar]

如果你有特定数据的 java 类,你会以 json 的形式获得。然后使用 Hymanson 库很容易提取数据。[下载:http: //repo1.maven.org/maven2/com/fasterxml/Hymanson/core/Hymanson-core/2.2.3/Hymanson-core-2.2.3.jar]

then Your code will be:

那么你的代码将是:

public String getParam(String code, String element) {

    String base = this.getElementById(code);
    ObjectMapper mapper = new ObjectMapper();
    Product product = mapper.readValue(base, Product.class);

    // this will return name of product
    return product.getItem()[0].getName();
}