При отправке запроса JSON POST в мой RESful API с запущенной Jetty я анализирую данные JSON, полученные в запросе, и пытаюсь сопоставить их с моим классом конструктора. Проблема возникает, когда полученные данные не находятся в точном расположении геттера / установщика.
Это похоже на то, что на самом деле он не сопоставляется с геттером / сеттером. Это то, что я использую для анализа JSON из запроса, когда он приходит:
Vehicle v = new Gson().fromJson(req.getReader(), Vehicle.class);
Я ожидал, что выходные данные будут правильно проанализированы, поскольку API должен просто прочитать каждый ключ и сопоставить его с геттером и сеттером, чтобы я мог получить к нему доступ как
v.getVehicle_id();
Однако при отправке данных JSON, которые не находятся в точном расположении геттера / установщика. Это вызывает ошибку, так как ожидает, что первое значение будет «vehicle_id» с целым числом, когда иногда оно получает другое значение, такое как «color» со строкой «black».
Есть ли лучший способ проанализировать JSON, когда он входит? Я должен использовать Gson, поскольку это для университетского назначения.
Это мой Vehicle.class
public Vehicle() {
}
/*
* Maps the database into this class so they can be used in the getter/setter, they are private as other classes don't need access to them
* This is because they go through the getters/setters, which are public.
*/
private int vehicle_id;
private String make;
private String model;
private int year;
private int price;
private String license_number;
private String colour;
private int number_doors;
private String transmission;
private int mileage;
private String fuel_type;
private int engine_size;
private String body_style;
private String condition;
private String notes;
public Vehicle(int vehicle_id, String make, String model, int
year, int price, String license_number, String colour, int
number_doors, String transmission, int mileage, String fuel_type,
int engine_size, String body_style, String condition, String
notes) {
this.vehicle_id = vehicle_id;
this.make = make;
this.model = model;
this.year = year;
this.price = price;
this.license_number = license_number;
this.colour = colour;
this.number_doors = number_doors;
this.transmission = transmission;
this.mileage = mileage;
this.fuel_type = fuel_type;
this.engine_size = engine_size;
this.body_style = body_style;
this.condition = condition;
this.notes = notes;
}
/*
* Creates the getter and setters which map to the database so they can be used by the Controller to store and retreieve data when needed.
*/
public int getVehicle_id() {
return vehicle_id;
}
public void setVehicle_id(int vehicle_id) {
this.vehicle_id = vehicle_id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getLicense_number() {
return license_number;
}
public void setLicense_number(String license_number) {
this.license_number = license_number;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public int getNumber_doors() {
return number_doors;
}
public void setNumber_doors(int number_doors) {
this.number_doors = number_doors;
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public String getFuel_type() {
return fuel_type;
}
public void setFuel_type(String fuel_type) {
this.fuel_type = fuel_type;
}
public int getEngine_size() {
return engine_size;
}
public void setEngine_size(int engine_size) {
this.engine_size = engine_size;
}
public String getBody_style() {
return body_style;
}
public void setBody_style(String body_style) {
this.body_style = body_style;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
Это мои данные JSON
{"colour":"Black","license_number":"DA98 7BK","body_style":"Small","engine_size":"1","number_doors":"Black","transmission":"manual","year":"2009","price":"10000","make":"Ford","vehicle_id":"8","notes":"Old","fuel_type":"Petrol","condition":"Old","mileage":"20000","model":"Ka"}
Это ошибка, которую я получаю с сервера
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "Black"
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:241)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:231)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at servlets.ServletApi.doPut(ServletApi.java:120)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:535)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:748)
Caused by:
java.lang.NumberFormatException: For input string: "Black"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.google.gson.stream.JsonReader.nextInt(JsonReader.java:1178)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:239)
at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:231)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at servlets.ServletApi.doPut(ServletApi.java:120)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:535)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1564)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.produce(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:748)```