【问题标题】:how to read json Array or Json Object in rest service?如何在休息服务中读取 json Array 或 Json Object?
【发布时间】:2018-02-25 01:56:10
【问题描述】:

我向下面提到的休息服务发送了XmlHttpRequest。我正在通过xhr.send() 方法向其余服务发送一组对象。

var object =[  
   {  
      "name":"John",
      "age":31,
      "city":"New York"
   },
   {  
      "name":"John",
      "age":31,
      "city":"New York"
   },
   {  
      "name":"John",
      "age":31,
      "city":"New York"
   }
];
      $scope.onSubmit = function () {
        var xhr = new XMLHttpRequest();
        var url = "http://localhost:8080/abcd/xyz/qwer";
        var params = '';
        xhr.open("POST", url , true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.setRequestHeader("Accept","application/json");
        xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {

            }
        };
    xhr.send(JSON.stringify(object) );
};

当我在没有 JsonObject 参数的情况下 ping 这个休息服务时,它会到达休息服务,但是当在休息服务中保持 JsonObject 作为其参数时,它会给出不支持的媒体类型 415 错误。在休息服务中,我正在尝试阅读通过 send() 方法发送的 json 但它会导致错误。

@POST
@Path("/qwer")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response Service(JsonArray object) {
    String name = object[0].name;
    String age = object[0].age;
    return Response.status(200).entity(" read data").build();

}

当我在没有 JsonObject 参数的情况下 ping 这个休息服务时,它会到达休息服务,但是当在休息服务中保持 JsonObject 作为其参数时,它会给出不支持的媒体类型 415 错误。在休息服务中,我正在尝试阅读通过 send() 方法发送的 json 如何在 rest 服务中读取 JsonArray 或 JsonObject ?

【问题讨论】:

    标签: java jersey xmlhttprequest jersey-2.0


    【解决方案1】:

    不要忘记定义/配置 Jackson MessageConverter

    public class AppConfig extends WebMvcConfigurerAdapter {
         ...     
    
         @Override
            public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    
                converters.add(new MappingJackson2HttpMessageConverter());
                super.configureMessageConverters(converters);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多