gpt4 book ai didi

java - 发送不带 'root' 的 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 16:16:07 25 4
gpt4 key购买 nike

使用Java RestEasy JSon API,在下一个WebService客户端代码中我想问你是否可以通过这种方式发送de Json对象:

{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}

...而不是这个:

{
"book" :
{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}
}

我的意思是我不想发送“根”元素“book”。

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
@XmlType(propOrder = {"title", "author", "price"})
public class Book {

private String title;
private String author;
private Double price;

public Book() {
super();
}

public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}

}

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.fasterxml.jackson.databind.ObjectMapper;

public class BookClient {

public static void main(String[] args) {

Response httpResponse = null;
try {
String url = "http://someserver/somepath/etc";

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(url);

Book libro1 = new Book();
libro1.setAuthor("Some author");
libro1.setPrice(99.9);
libro1.setTitle("Some title book");

String jsonEnviado = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(libro1);

Entity<Book> entidad = Entity.entity(libro1, "application/json");
httpResponse = target.request().post(entidad);

Respuesta respuesta = httpResponse.readEntity(Respuesta.class);
if (respuesta != null) {
String jsonRecibido = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(respuesta);
}

int status = httpResponse.getStatus();
if (status == 200) {
logTexto = "OK. Status: " + status;
System.out.println(logTexto);
} else {
logTexto = "KO. Status: " + status;
throw new Exception(logTexto);
}

} catch(Exception e) {
System.out.println("EXCEPTION! " + e.getMessage());
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (Exception e) {
//IGNORE IT
}
}
}

}

}

谢谢!

最佳答案

最后我用它来避免发送根元素“book”:

//Entity<Book> entidad = Entity.entity(libro1, "application/json");
//httpResponse = target.request().post(entidad);

Entity<String> entidad = Entity.entity(jsonEnviado, "application/json");
httpResponse = target.request().post(entidad);

关于java - 发送不带 'root' 的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62386880/

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