Peine y explique el uso de JsonObject y JsonArray [ejemplos de cadenas JSON complejas en la historia para explicar]

Procesamiento común de cadenas JSON en la vida diaria, este artículo utilizará cadenas JSON complejas para clasificar y explicar el uso de JsonObject y JsonArray.

Tenemos datos JSON complejos como se muestra a continuación.

Antes de leer la explicación detallada, se recomienda que analice la siguiente estructura de cadena json en la vista json para observarla bien, lo que facilitará su comprensión y logrará el doble de resultado con la mitad del esfuerzo.

{
    "_index": "t_spider_gat_log_20230622",
    "_type": "_doc",
    "_id": "YyUp4ogBrZfsTXIOIzYJ",
    "_version": 1,
    "_score": null,
    "_source": {
        "msg": "success",
        "code": 0,
        "responseTime": "2023-06-22T08:12:06.791Z",
        "channel": "",
        "responseJSON": "{\"code\":0,\"createTime\":\"\",\"itineraries\":[{\"prices\":[{\"bookingCode\":\"T\",\"currency\":\"NOK\",\"fareFamilyType\":\"LowFare\",\"paxType\":\"ADT\",\"price\":2110.0,\"seatCount\":9,\"tax\":482.0},{\"bookingCode\":\"T\",\"currency\":\"NOK\",\"fareFamilyType\":\"LowFare+\",\"paxType\":\"ADT\",\"price\":2560.0,\"seatCount\":9,\"tax\":482.0},{\"bookingCode\":\"A\",\"currency\":\"NOK\",\"fareFamilyType\":\"Flex\",\"paxType\":\"ADT\",\"price\":5160.0,\"seatCount\":9,\"tax\":482.0}],\"segments\":[{\"airline\":\"DY\",\"arrAirport\":\"BGO\",\"arrTerminal\":\"\",\"arrTime\":\"202310011245\",\"codeShare\":false,\"direction\":1,\"dptAirport\":\"LGW\",\"dptTerminal\":\"\",\"dptTime\":\"202310010950\",\"duration\":115,\"equipment\":\"73H\",\"flightNo\":\"DY1317\",\"go\":true,\"operatingAirline\":\"\",\"operatingFlightNo\":\"\",\"return\":false,\"stopCities\":\"\"},{\"airline\":\"DY\",\"arrAirport\":\"BGY\",\"arrTerminal\":\"\",\"arrTime\":\"202310012035\",\"codeShare\":false,\"direction\":1,\"dptAirport\":\"BGO\",\"dptTerminal\":\"\",\"dptTime\":\"202310011805\",\"duration\":150,\"equipment\":\"73H\",\"flightNo\":\"DY1848\",\"go\":true,\"operatingAirline\":\"\",\"operatingFlightNo\":\"\",\"return\":false,\"stopCities\":\"\"}]}],\"msg\":\"success\"}",
        "source": "SER",
        "reqId": "GAT_SER_f6ebd7b8771647f393fcdc4e0fd77ced",
        "vendorCode": "ADY",
        "requestJSON": "{\"application\":\"API\",\"channel\":\"\",\"condition\":{\"adtCount\":2,\"arrAirports\":[\"BGY\",\"LIN\",\"MXP\",\"PMF\"],\"arrCity\":\"MIL\",\"chdCount\":0,\"dptAirports\":[\"LCY\",\"LGW\",\"LHR\",\"LTN\",\"SEN\",\"STN\"],\"dptCity\":\"LON\",\"dptDate\":\"2023-10-01\",\"infCount\":0,\"rtnDate\":\"\",\"singleTrip\":true,\"tripType\":1},\"realTime\":false,\"region\":\"SG\",\"requestId\":\"GAT_SER_f6ebd7b8771647f393fcdc4e0fd77ced\",\"requestTime\":1687421526160,\"scriptDirectory\":\"ady\",\"source\":\"SER\",\"useProxy\":true,\"vendorCode\":\"ADY\"}",
        "requestTime": "2023-06-22T08:12:06.160Z",
        "proxy": null,
        "requestTimeEnd": null,
        "application": "API",
        "subOrderNumber": null,
        "action": "GAT",
        "requestTimeStart": null,
        "airline": null,
        "region": "SG",
        "status": "COMPLETE"
    },
    "fields": {
        "requestTime": [
            "2023-06-22T08:12:06.160Z"
        ],
        "responseTime": [
            "2023-06-22T08:12:06.791Z"
        ]
    },
    "highlight": {
        "responseJSON": [
            "{\"code\":0,\"createTime\":\"\",\"itineraries\":[{\"prices\":[{\"bookingCode\":\"T\",\"currency\":\"NOK\",\"fareFamilyType\":\"LowFare\",\"paxType\":\"ADT\",\"@kibana-highlighted-field@price@/kibana-highlighted-field@\":2110.0,\"seatCount\":9,\"tax\":482.0},{\"bookingCode\":\"T\",\"currency\":\"NOK\",\"fareFamilyType\":\"LowFare+\",\"paxType\":\"ADT\",\"@kibana-highlighted-field@price@/kibana-highlighted-field@\":2560.0,\"seatCount\":9,\"tax\":482.0},{\"bookingCode\":\"A\",\"currency\":\"NOK\",\"fareFamilyType\":\"Flex\",\"paxType\":\"ADT\",\"@kibana-highlighted-field@price@/kibana-highlighted-field@\":5160.0,\"seatCount\":9,\"tax\":482.0}],\"segments\":[{\"airline\":\"DY\",\"arrAirport\":\"BGO\",\"arrTerminal\":\"\",\"arrTime\":\"202310011245\",\"codeShare\":false,\"direction\":1,\"dptAirport\":\"LGW\",\"dptTerminal\":\"\",\"dptTime\":\"202310010950\",\"duration\":115,\"equipment\":\"73H\",\"flightNo\":\"DY1317\",\"go\":true,\"operatingAirline\":\"\",\"operatingFlightNo\":\"\",\"return\":false,\"stopCities\":\"\"},{\"airline\":\"DY\",\"arrAirport\":\"BGY\",\"arrTerminal\":\"\",\"arrTime\":\"202310012035\",\"codeShare\":false,\"direction\":1,\"dptAirport\":\"BGO\",\"dptTerminal\":\"\",\"dptTime\":\"202310011805\",\"duration\":150,\"equipment\":\"73H\",\"flightNo\":\"DY1848\",\"go\":true,\"operatingAirline\":\"\",\"operatingFlightNo\":\"\",\"return\":false,\"stopCities\":\"\"}]}],\"msg\":\"success\"}"
        ]
    },
    "sort": [
        1687421526160
    ]
}

Para analizar estos datos JSON, primero los convertimos a JSONObject y luego obtenemos JSONObject o JSONArray anidados donde sea necesario.

Convertir a JSONObject

import org.json.JSONObject;
import org.json.JSONArray;

// 假设 jsonString 是您提供的 JSON 字符串

// 将字符串转化为 JSONObject
JSONObject jsonObj = new JSONObject(jsonString);

parsing_source

Para entender mejor a todos, obtendré el análisis de campo más complicado _fuente para explicar

// 获取 _source 的 JSONObject
JSONObject source = jsonObj.getJSONObject("_source");

// 获取 _source 中的各种值
String msg = source.getString("msg");
int code = source.getInt("code");
String responseTime = source.getString("responseTime");
String channel = source.getString("channel");

analizar respuestaJSON

// 获取 _source 中的 responseJSON 并转化为另一个 JSONObject
String responseJSONString = source.getString("responseJSON");
JSONObject responseJSON = new JSONObject(responseJSONString);

itinerarios de análisis

// 从 responseJSON 中获取 itineraries,它是一个 JSONArray
JSONArray itineraries = responseJSON.getJSONArray("itineraries");

// 遍历每一个 itinerary
for (int i = 0; i < itineraries.length(); i++) {
    
    
    // 获取每一个 itinerary,它是一个 JSONObject
    JSONObject itinerary = itineraries.getJSONObject(i);

análisis de precios

// 从 itinerary 中获取 prices,它是一个 JSONArray
JSONArray prices = itinerary.getJSONArray("prices");

// 遍历每一个 price
for (int j = 0; j < prices.length(); j++) {
    
    
    // 获取每一个 price,它是一个 JSONObject
    JSONObject price = prices.getJSONObject(j);

    // 从 price 中获取各种值
    String bookingCode = price.getString("bookingCode");
    String currency = price.getString("currency");
    String fareFamilyType = price.getString("fareFamilyType");
    String paxType = price.getString("paxType");
    double priceValue = price.getDouble("price");
    int seatCount = price.getInt("seatCount");
    double tax = price.getDouble("tax");
}

NOTA: Este código no maneja posibles excepciones. En la práctica, es posible que deba ajustar estas llamadas para manejar posibles excepciones como JSONException.

análisis de segmentos

En cada itinerario, también hay un JSONArray de segmentos, también podemos analizar este conjunto.

// 从 itinerary 中获取 segments,它是一个 JSONArray
JSONArray segments = itinerary.getJSONArray("segments");

// 遍历每一个 segment
for (int k = 0; k < segments.length(); k++) {
    
    
    // 获取每一个 segment,它是一个 JSONObject
    JSONObject segment = segments.getJSONObject(k);

    // 从 segment 中获取各种值
    String airline = segment.getString("airline");
    String arrAirport = segment.getString("arrAirport");
    String arrTerminal = segment.getString("arrTerminal");
    String arrTime = segment.getString("arrTime");
    boolean codeShare = segment.getBoolean("codeShare");
    int direction = segment.getInt("direction");
    String dptAirport = segment.getString("dptAirport");
    String dptTerminal = segment.getString("dptTerminal");
    String dptTime = segment.getString("dptTime");
    int duration = segment.getInt("duration");
    String equipment = segment.getString("equipment");
    String flightNo = segment.getString("flightNo");
    boolean go = segment.getBoolean("go");
    String operatingAirline = segment.getString("operatingAirline");
    String operatingFlightNo = segment.getString("operatingFlightNo");
    boolean returnFlag = segment.getBoolean("return");
    String stopCities = segment.getString("stopCities");
}

En el código anterior, obtuvimos la matriz de segmentos, luego atravesamos cada segmento y obtuvimos varios valores de él. Este proceso es similar al proceso anterior, excepto que la matriz de segmentos está involucrada en lugar de la matriz de precios.

Resumir:

Así es como analizamos datos JSON complejos. Tenga en cuenta que estamos usando la biblioteca org.json, que es una biblioteca de Java muy poderosa y de uso común para manipular JSON. ¡Espero que este ejemplo te ayude!

Supongo que te gusta

Origin blog.csdn.net/m0_49303490/article/details/131342500
Recomendado
Clasificación