![](/img/trans.png)
[英]Android - JSON - How do I create a JSON Object & JSON Array to match this format using JSONObject & JSONArray Types?
[英]How do I format the results of a JSONArray
所以我想在這里使用 API: https://clinicaltables.nlm.nih.gov/apidoc/icd10cm/v3/doc.html#output
到目前為止,這是我的代碼:
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
public class DiagnosesAPIHelper
{
public static void main(String[] args)
{
try
{
URL url = new URL ("https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name&terms=tuberc");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if(responseCode != 200)
{
throw new Exception("HTTP Response code: " + responseCode);
}
else
{
String inline = "";
Scanner scanner = new Scanner(url.openStream());
//Write all the JSON data into a string using a scanner
while (scanner.hasNext()) {
inline += scanner.nextLine();
}
//Close the scanner
scanner.close();
//Using the JSON simple library parse the string into a json object
JSONParser parse = new JSONParser();
JSONArray jsonArray = (JSONArray) parse.parse(inline);
System.out.println(jsonArray.get(3).toString());
}} catch (Exception e) {
e.printStackTrace();
}
}
}
這是我得到的輸出:
[["A15.0","Tuberculosis of lung"],["A15.4","Tuberculosis of intrathoracic lymph nodes"],["A15.5","Tuberculosis of larynx, trachea and bronchus"],["A15.6","Tuberculous pleurisy"],["A15.7","Primary respiratory tuberculosis"],["A15.8","Other respiratory tuberculosis"],["A15.9","Respiratory tuberculosis unspecified"]]
我將如何提取 ICD 代碼和診斷描述?
所以我得到的是 [["A15.0","肺結核"]
我如何從中制作出 2 個字符串,一個用於 A15.0 部分,另一個用於肺結核部分。
我可以將其標記化,但這需要大量工作。 必須有更簡單的方法。
提前致謝
為了迭代 JSON 數組的元素,您必須將返回的通用 object 轉換為JSONArray
。
在您的示例jsonArray.get(3)
返回一個通用的 object,因為在 JSON 中,您可以擁有不同類型的對象,例如數字、字符串和數組。
但是,您知道jsonArray.get(3)
返回一個數組,因此如果您強制轉換,您可以像處理數組或列表一樣處理結果。
這是您可以在System.out.println(jsonArray.get(3).toString());
之后放置的示例
JSONArray elements = (JSONArray) jsonArray.get(3);
for (Object element : elements) {
JSONArray elementJSONArray = (JSONArray) element;
System.out.println("code: " + elementJSONArray.get(0));
System.out.println("description: " + elementJSONArray.get(1));
}
Output
code: A15.0
description: Tuberculosis of lung
code: A15.4
description: Tuberculosis of intrathoracic lymph nodes
code: A15.5
description: Tuberculosis of larynx, trachea and bronchus
code: A15.6
description: Tuberculous pleurisy
code: A15.7
description: Primary respiratory tuberculosis
code: A15.8
description: Other respiratory tuberculosis
code: A15.9
description: Respiratory tuberculosis unspecified
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.