【发布时间】:2019-06-12 19:23:24
【问题描述】:
我正在学习如何在休息服务中生成和使用 JSON,但我想学好它,所以我尝试了所有可能的对象案例,其中一个是具有此类 List 属性的对象:
import java.util.List;
public class PruebaJSON {
private String nombre;
private List atributos;
private String descripcion;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List getAtributos() {
return atributos;
}
public void setAtributos(List atributos) {
this.atributos = atributos;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
}
那么我在我的休息服务方法上所做的就是这样:
@POST
@Path("/prueba")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PruebaJSON prueba(String data) {
try {
JSONObject json = new JSONObject(data);
Gson convertir = new GsonBuilder().create();
PruebaJSON pruebaJson = convertir.fromJson(json.toString(), PruebaJSON.class);
return pruebaJson;
} catch (Exception e) {
System.out.println("error " + e);
return null;
}
}
然后在 POSTMAN 中我传递这个:
{
"descripcion": "Primera prueba",
"nombre": "Prueba 1",
"atributos": [
"hello",
"kek",
"lul"
]
}
它工作正常,问题是当我尝试用Java做同样的事情时,例如:
List atributos = new ArrayList<>();
atributos.add("hello");
atributos.add("kek");
atributos.add("lul");
System.out.println(bus.prueba("Prueba 1", "Primera Prueba", atributos));
bus.prueba 只是执行服务,但随后在控制台中出现此错误:
14:16:56,567 INFO [stdout] (default task-2) error com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 66 path $.atributos
我搜索了错误并发现了这个: Gson: Expected begin_array but was STRING
我了解错误但有什么解决方案? 我无法真正控制 JSON 如何构建数组列表,可以吗? 这是我客户端中的 prueba 方法:
public String prueba(String nombre, String descripcion, List atributos) {
HashMap map = new HashMap<>();
map.put("nombre", nombre);
map.put("descripcion", descripcion);
map.put("atributos", atributos);
String respuesta = utilidadesRestSeguridad.consumir("prueba", map);
return respuesta;
}
在我的客户端组件中,这是构建 json 的方法:
public static JsonObject generateJSON(HashMap map) throws MalformedURLException {
JsonObject json = new JsonObject();
for (Object key : map.keySet()) {
json.addProperty(key.toString(), map.get(key).toString());
}
return json;
}
如果您想查看更多代码或我来解释某些内容,请告诉我,感谢您的帮助。
我认为由于 .toString(),错误可能出在方法 generateJSON 中,但是我应该如何处理这种情况?
【问题讨论】:
-
警告:您使用的是原始类型(
List和HashMap)。永远不要在新代码中使用它们。 -
为什么这么糟糕? :o
-
因为您失去了类型安全性,使您的代码容易出错。 More about the usage of raw types.