简体   繁体   English

如何访问 java 中的嵌套 Json 数组数据

[英]How to Acces nested Json Array data in java

I was trying to extract data from JSON in Java.我试图从 Java 中的 JSON 中提取数据。

在此处输入图像描述

have any idea about how to access these JSON data which is underlined in blue it is nested JSON array I guess?对如何访问这些用蓝色下划线的 JSON 数据有任何想法,我猜它是嵌套的 JSON 数组? I know about JSON object and getstring(key) but it is working only for these data which is underlined in red.我知道 JSON object 和 getstring(key) 但它仅适用于红色下划线的这些数据。 I want that blueline data.我想要那个蓝线数据。 Any solution would be great.任何解决方案都会很棒。 Any help would be useful for me I am working on this issue for the last 5 days.任何帮助都会对我有用,我在过去 5 天里一直在处理这个问题。 Java Code Java代码

JSONObject object = (JSONObject) new JSONTokener(response).nextValue();

response is a string which contain json data. response 是一个包含 json 数据的字符串。

{
    "calories":115,
    "totalWeight":223.0,
    "dietLabels":["LOW_FAT"],
    "healthLabels":["VEGAN","VEGETARIAN","PEANUT_FREE","TREE_NUT_FREE","ALCOHOL_FREE","SULPHITE_FREE"],
    "cautions":["SULFITES"],
    "totalNutrients":{
        "ENERC_KCAL": {"label":"Energy","quantity":115.96,"unit":"kcal"},
        "FAT":{"label":"Fat","quantity":0.37910000000000005,"unit":"g"},
        "FASAT":{"label":"Saturated","quantity":0.06244,"unit":"g"},
        "FAMS":{"label":"Monounsaturated","quantity":0.01561,"unit":"g"},
        "FAPU":{"label":"Polyunsaturated","quantity":0.11373,"unit":"g"},
        "CHOCDF":{"label":"Carbs","quantity":30.796300000000002,"unit":"g"},
        "FIBTG":{"label":"Fiber","quantity":5.351999999999999,"unit":"g"},
        "SUGAR":{"label":"Sugars","quantity":23.169700000000002,"unit":"g"},
        "PROCNT":{"label":"Protein","quantity":0.5798,"unit":"g"},
        "CHOLE":{"label":"Cholesterol","quantity":0.0,"unit":"mg"}
    }
}

You can call你可以打电话

JSONArray dietLabels = jo.getJSONArray("dietLabels");

To access ENERC_KCAL Data you can do something like that:要访问 ENERC_KCAL 数据,您可以执行以下操作:

JSONObject totalNutrients = jo.getJSONObject("totalNutrients");
JSONObject ENERC_KCAL = totalNutrients.getJSONObject("ENERC_KCAL");

on the JsonObject where jo is the main json object (from the given json string) and "dietLabels" is the name of the array.在 JsonObject 上,其中 jo 是主要的 json object(来自给定的 json 字符串),“dietLabels”是数组的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM