【发布时间】:2021-11-15 18:13:01
【问题描述】:
我实现了我想要实现的目标,但是,我对实现目标的不必要的(?)字符串解析并不满意。
这里是简化的代码:
HttpURLConnection con = null;
URL url = new URL(URL);
con = (HttpURLConnection) url.openConnection();
// set connection parameters and make a GET-call
con.setRequestMethod("GET");
//Must be a better way?
InputStream inputStream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String 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());
// I only want the child-node
String myArray = jsonNode.get("parent").get("child").toString();
// Map the response to my object
List<Car> car = objectMapper.readValue(myArray, new TypeReference<List<Car>>(){});
有很多类似的手动解析
- 将Http连接输入流读取到
StringBuilder,然后调用toString()。 - 检索
JsonNode并调用toString()
jsonNode.get("parent").get("child").toString()
实现我的目标。我绝不是任何高级开发人员,我很乐意听取建议以及如何删除“不必要的”解析。
- API 调用的响应已经是 JSON 格式了
- API 调用只能使用 HttpURLConnection-class。
我的汽车课:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"color"})
public class Car {
@JsonProperty("id")
public String id;
@JsonProperty("color")
public String color;
}
【问题讨论】:
-
'同一个字符串有很多解析':不,没有。响应字符串只有一次解析。
标签: java objectmapper httpconnection