【问题标题】:Avoid calling toString with Objectmapper [Java 8]避免使用 Objectmapper [Java 8] 调用 toString
【发布时间】: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>>(){});

有很多类似的手动解析

  1. 将Http连接输入流读取到StringBuilder,然后调用toString()。
  2. 检索JsonNode 并调用toString()
jsonNode.get("parent").get("child").toString()

实现我的目标。我绝不是任何高级开发人员,我很乐意听取建议以及如何删除“不必要的”解析。

  1. API 调用的响应已经是 JSON 格式了
  2. 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


【解决方案1】:

很高兴看到您想改进您的代码。 将输入流读取到StringBuilder 并调用jsonNode.toString() 确实没有必要。在大多数情况下,总有一个有用的 API 可以满足您的需求。 这是我的建议:

  1. 使用ObjectMapper#readTree(InputStream) 来简化使用HTTP 输入流的部分。
JsonNode jsonNode = objectMapper.readTree(con.getInputStream());
  1. 检索到目标JsonNode后,创建JsonParser然后调用
JsonParser jsonParser = new TreeTraversingParser(jsonNode.get("parent").get("child"));
objectMapper.readValue(jsonParser,new TypeReference<List<Car>>(){});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多