我實作了我想要實作的目標,但是,我對為了達到我的目標而進行的不必要的(?)字串決議不滿意。
下面是簡化后的代碼:
HttpURLConnection con = null。
URL url = new URL(URL)。
con = (HttpURLConnection) url.openConnection();
//設定連接引數并進行GET-呼叫。
con.setRequestMethod("GET")。
//Must be a better way?
InputStream inputStream = con.getInputStream()。
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)) 。
StringBuilder response = new StringBuilder() 。
字串currentLine。
//Build the string from the response from con.
while ((currentLine = in.readLine()) != null)
response.append(currentLine);
in.close()。
ObjectMapper objectMapper = new ObjectMapper() 。
JsonNode jsonNode = objectMapper.readTree(response.toString() )。
//我只想要子節點
String myArray = jsonNode.get("parent").get("child").toString()。
//將回應映射到我的物件。
List<Car> car = objectMapper.readValue(myArray, new TypeReference<List<Car> >(){})。
有太多的手動決議,如
- 讀取Http的資料。
- 讀取Http連接輸入流到
StringBuilder,然后呼叫toString()。 - 檢索
JsonNode并呼叫toString()。
jsonNode.get("parent").get("child").toString()
為了實作我的目標。我絕不是什么高級開發人員,我很樂意接受建議以及如何去除 "不必要的 "決議。
- 來自 API 呼叫的回應已經是 JSON 格式 。
- 只能使用HttpURLConnection類進行API呼叫。
我的汽車類:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"顏色"})
public class Car {
@JsonProperty("id")
public String id;
@JsonProperty("color")
public String color;
}
uj5u.com熱心網友回復:
很高興看到你想改進你的代碼。
讀取輸入流到StringBuilder并呼叫jsonNode.toString()確實沒有必要。在大多數情況下,總是有一個有用的API來滿足你的需求。
以下是我的建議:
- 使用ObjectMapper#readTree(InputStream)來簡化消費HTTP輸入流的部分。
JsonNode jsonNode = objectMapper.readTree(con.getInputStream())。
- 在檢索到目標
JsonNode后,創建一個JsonParser,然后呼叫
JsonParser jsonParser = new TreeTraversingParser(jsonNode. get("parent").get("child"))。)
objectMapper.readValue(jsonParser,new TypeReference<List<Car>>(){})。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333333.html
標籤:
