如何将一个字符串分隔为 java 中的多个 json 对象?
how can i Separate a string to many json object in java?
我需要一些帮助:我有一个通过 http GET 请求获得的字符串,在这个字符串中有很多项目写成 json 我的问题是如何分离或检索这个项目并保存它作为 json 文件
这是我打印回复的方式:
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
这可能对你有用:
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String responseBody ="{ \"result\": [ { \"name\": \"tom\", \"gender\": \"male\", \"address\": {\"city\": \"NY\", \"town\": \"US\"}, \"age\": \"20\"}, { \"name\": \"sarah\", \"gender\": \"female\", \"address\": {\"city\": \"NY\", \"town\": \"US\"}, \"age\": \"22\"}] } ";
JsonNode jsonNode = objectMapper.readValue(responseBody, JsonNode.class);
JsonNode jsonArray =jsonNode.get("result");
if (jsonArray.isArray()) {
for (JsonNode objNode : jsonArray) {
String fileName = String.format( "file%s.json",objNode.get("name").asText());
objectMapper.writeValue(new File(fileName), objNode);
}
}
}
}
在这里,我将 responseBody
转换为 JsonNode 对象,然后迭代 result
字段的每个元素和将其保存为文件。
我需要一些帮助:我有一个通过 http GET 请求获得的字符串,在这个字符串中有很多项目写成 json 我的问题是如何分离或检索这个项目并保存它作为 json 文件
这是我打印回复的方式:
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
这可能对你有用:
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String responseBody ="{ \"result\": [ { \"name\": \"tom\", \"gender\": \"male\", \"address\": {\"city\": \"NY\", \"town\": \"US\"}, \"age\": \"20\"}, { \"name\": \"sarah\", \"gender\": \"female\", \"address\": {\"city\": \"NY\", \"town\": \"US\"}, \"age\": \"22\"}] } ";
JsonNode jsonNode = objectMapper.readValue(responseBody, JsonNode.class);
JsonNode jsonArray =jsonNode.get("result");
if (jsonArray.isArray()) {
for (JsonNode objNode : jsonArray) {
String fileName = String.format( "file%s.json",objNode.get("name").asText());
objectMapper.writeValue(new File(fileName), objNode);
}
}
}
}
在这里,我将 responseBody
转换为 JsonNode 对象,然后迭代 result
字段的每个元素和将其保存为文件。