gpt4 book ai didi

Java.net(RestFul服务JSON响应解析问题) 如何将JSON响应字符串中的相同项目列表转换为Java对象?

转载 作者:行者123 更新时间:2023-11-30 06:10:05 27 4
gpt4 key购买 nike

我正在使用以下代码调用 Restful 服务:(Java.net 实现)

StringBuilder responseStrBuilder = new StringBuilder();

try
{
URL url = new URL(restUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(httpRequestMethod);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/json");

if (requestHeaders != null)
{
for (Map.Entry<String, String> entry : requestHeaders.entrySet())
{
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}

conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
os.write(urlParameters.getBytes());
os.flush();
os.close();

if (conn.getResponseCode() != 200) {//do something}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

while ((output = br.readLine()) != null)
responseStrBuilder.append(output);

方法 1:我有以下字符串(JSON String)作为我的 Restful 服务响应,如何将其转换为 Java 对象。由于如果我使用 org.codehaus.jettison.json.JSONObject myObject = new org.codehaus.jettison.json.JSONObject(responseStrBuilder.toString()); ,则相同(Itm)对象会重复多次它只读取第一个 Itm 对象,不带所有 item 对象的列表。

服务的 JSON 字符串输出:

{"Response":{"RID":"04'34'",
"Itm":{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
"Itm":{"id":{"ab":"2","cd":"34},"qw":"JK","name":"asdf "},
"Itm":{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}
}}

方法 2:我还尝试了下面的代码片段,其中包含带有 setter 和 getter 的正确 Java 对象

ObjectMapper objectMapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyJavaReponseObject javaObj = mapper.readValue(json, MyJavaReponseObject.class);

这种方法也只读取 Itm 的一个对象,而不是所有对象,因为它不是 JSON 字符串中的数组格式。有没有更好的方法将所有对象(Itm)映射到 java pojo 中的单个对象列表?

最佳答案

如果您应该解析该 json 字符串本身,则可以在响应对象中使用 List 类。

我有一个 ReponseJSON 类,其中包含 json 对象、一个 Response 和三个 Itms

static class ReponseJSON {
private Response Response;

@JsonProperty("Response")
public Response getResponse() {
return Response;
}

public void setResponse(Response Response) {
this.Response = Response;
}

static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();

public Itm getItm() {
return Itm;
}

@JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}

public String getRID() {
return rid;
}

public List<Itm> getItms() {
return listItm;
}

@JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}

static class Itm {
private Id id;

private String qw, name;

public String getQw() {
return qw;
}

public void setQw(String qw) {
this.qw = qw;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Id getId() {
return id;
}

public void setId(Id id) {
this.id = id;
}

static class Id {
private String ab, cd;

public String getCd() {
return cd;
}

public void setCd(String cd) {
this.cd = cd;
}

public String getAb() {
return ab;
}

public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}

在 Response 类中,我有一个列表类,并在对象映射器调用此类时保存 Itm 对象。

static class Response {
... skip ..
private List<Itm> listItm = new ArrayList<Itm>();
... skip ..
@JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
}

查看完整源代码如下。

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonParserTest {

static class ReponseJSON {
private Response Response;

@JsonProperty("Response")
public Response getResponse() {
return Response;
}

public void setResponse(Response Response) {
this.Response = Response;
}

static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();

public Itm getItm() {
return Itm;
}

@JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}

public String getRID() {
return rid;
}

public List<Itm> getItms() {
return listItm;
}

@JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}

static class Itm {
private Id id;

private String qw, name;

public String getQw() {
return qw;
}

public void setQw(String qw) {
this.qw = qw;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Id getId() {
return id;
}

public void setId(Id id) {
this.id = id;
}

static class Id {
private String ab, cd;

public String getCd() {
return cd;
}

public void setCd(String cd) {
this.cd = cd;
}

public String getAb() {
return ab;
}

public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}

public static void main(String[] args) {

String responseJson =
"{\"Response\":{\"RID\":\"04'34'\","
+ "\"Itm\":{\"id\":{\"ab\":\"1\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"abcd\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"2\",\"cd\":\"34\"},\"qw\":\"JK\",\"name\":\"asdf\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"3\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"fghj\"}"
+ "}} ";

ObjectMapper mapper = new ObjectMapper();

ReponseJSON responseObj = null;

try {
responseObj = mapper.readValue(responseJson, ReponseJSON.class);
ReponseJSON.Response response = responseObj.getResponse();

for(int i = 0; i < response.getItms().size(); i++)
{
ReponseJSON.Response.Itm item = response.getItms().get(i);

System.out.println(item.getId().getAb());
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

我的 Jackson Mapper 的版本是 2.9.1。

你检查源码的main方法,因为你准备的JSON字符串是无效的,正如coddemonkey提到的。

enter image description here

祝你有美好的一天。

关于Java.net(RestFul服务JSON响应解析问题) 如何将JSON响应字符串中的相同项目列表转换为Java对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com