gpt4 book ai didi

java - SpringMVC发送JSON数据到服务器(java)

转载 作者:行者123 更新时间:2023-12-02 06:38:46 29 4
gpt4 key购买 nike

我有一个javascript数组,我用数组结构的元素填充该数组:

 var citizens1 = [{"startLat":null,"startLng":null,"socialSecurityNumber":null}];

数组获取数据,但是我需要将此数据推送到服务器进行处理。该数组包含500 条记录。我没有向服务器发出 500 个 Web 服务请求,而是将数组数据转换为 JSON 字符串,并将所有数据传递到服务器,在服务器上我一次处理所有记录,从而使一次 ajax 调用

我不确定我是否将数据正确传递到服务器。我遇到错误。下面是我的代码:

Javascript

 citizens1.push({startLat:marker[index].getPosition().lat(),startLng:marker[index].getPosition().lng(),socialSecurityNumber:global_citizens[index].socialSecurityNumber});

if(citizens1.length == 500){
console.log('500 records saved');
window.clearTimeout( timerHandle);

for(var i = 0; i < citizens1.length ; i++){
var myJsonString = JSON.stringify(citizens1);
//console.log(myJsonString);

//console.log(citizens1[i].lat +',' +citizens1[i].lng+','+citizens1[i].socialSecurityNumber);
$.ajax({
type:'POST',
url:'logMovement.htm',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
data:myJsonString,
dataType: 'json',
success:function(data){

if (data == false){
console.log('error occured in logging data');
}

}

});

}

citizens1 = [];
}

Controller

 @RequestMapping(value="logMovement.htm", method={RequestMethod.POST},produces = "application/json; charset=utf-8")
public @ResponseBody Movement logMovement(@RequestBody Movement movement)throws Exception{

logger.info("About to log movement");

JSONObject jsonObj = JSONObject.fromObject(movement);
ObjectMapper mapper = new ObjectMapper();

List<Movement> move = mapper.readValue(jsonObj.toString(), new TypeReference<Movement>(){});

logger.info(move);
return null;

/*if((!lat.equals(null)) || (!(lat == null)) || (!(lat.length() == 0))){
double dLat = Double.parseDouble(lat);
double dLng = Double.parseDouble(lng);
int iSocialSecurityNumber = Integer.parseInt(socialSecurityNumber);

this.markerManager.logMovement(dLat, dLng, iSocialSecurityNumber);

}*/


}

运动等级

public class Movement implements Serializable{

private List<Integer>socialSecurityNumber;
private List<Double> startLat;
private List<Double> startLng;
/**
* @param socialSecurityNumber
* @param startLat
* @param startLng
*/

public Movement(){}

public Movement(List<Integer> socialSecurityNumber, List<Double> startLat,
List<Double> startLng) {
super();
this.socialSecurityNumber = socialSecurityNumber;
this.startLat = startLat;
this.startLng = startLng;
}
//getters and setters

发布到服务器的 Json 数据示例

我看到第一行是“空”,我不确定这是否导致问题

[{"startLat":null,"startLng":null,"socialSecurityNumber":null},{"startLat":10.537749449700717,"startLng":-61.44420048947677,"socialSecurityNumber":198501012},{"startLat": 10.537208514171011,"startLng":-61.443589321013235,"socialSecurityNumber":198501012},{"startLat":10.536667622323245,"startLng":-61.44297811322531,"socialSecurityNumber":19 8501012},{"startLat":10.536131483465244,"startLng":-61.442362603115384 ,"socialSecurityNumber":198501012},{"startLat":10.53566878133931,"startLng":-61.44168979108997,"socialSecurityNumber":198501012},{"startLat":10.535227295591238,"startLng":-61. 441000943386825,"社会保障号码":198501012}, {“startLat”:10.170058041417015,“startLng”:-61.67893982108137,“socialSecurityNumber”:194302025}

错误

我正在查看这个处理该问题的SO问题 Required JSON parameter is not present in jQuery Datatables

org.springframework.http.converter.HttpMessageNotReadableException:无法读取 JSON:无法从 START_ARRAY token 中反序列化 com.crimetrack.business.Movement 的实例

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.crimetrack.business.Movement out of START_ARRAY token
at [Source: org.apache.catalina.connector.CoyoteInputStream@72f1db9d; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.crimetrack.business.Movement out of START_ARRAY token
at [Source: org.apache.catalina.connector.CoyoteInputStream@72f1db9d; line: 1, column: 1]
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:127)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:120)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:91)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:71)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.crimetrack.business.Movement out of START_ARRAY token
at [Source: org.apache.catalina.connector.CoyoteInputStream@72f1db9d; line: 1, column: 1]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:159)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:131)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeUsingCreator(BeanDeserializer.java:397)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:296)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1282)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:941)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:124)
... 33 more

最佳答案

您的 JSON 无效,冒号左侧的值必须是字符串。

[
{
"lat": null,
"lng": null,
"socialSecurityNumber": null
}
]

此外,您似乎使用了错误的注释,@RequestBody 用于解析 JSON 的内容,而不是用于从中获取变量的 @RequestParam

这样的参数

?var=1&newvar=2

此外,在您的 JavaScript 中,将 data:{'myData':myJsonString } 更改为 data:myJsonString,

您应该创建一个愚蠢的对象来填充,请查看页面底部的本教程,其中他们填充了一个愚蠢的 Person 对象 hmkcode.com/spring-mvc-json-json-to-java

关于java - SpringMVC发送JSON数据到服务器(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362955/

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