No message body writer has been found for class com.alibaba.fastjson2.JSONObject, ContentType: */*

项目场景:

`提示:当你找到这篇文章时,你可能因为在webservice开发返回值时遇到了难题,这篇文章将帮你解决这个问题。

1:webservice当使用 cxf 发布服务时,要求返回值类型为xml,或者json等

@Path("/searchProductByText")

@GET

@Produces({"application/xml", "application/json"})

JSONObject productSearch(@QueryParam("text") String text);

但是 cxf不支持解析 JSONObject ,Map等对象

进行访问时将会返回 No message body writer has been found for class com.alibaba.fastjson.JSONObject, ContentType: * /*


解决方案:

2.解决方法,定义一个pojo,里面包含 JSONObject 引用。将返回的JSONObject包含在 自定义的 POJO中,使用注解将pojo定义为能被解析为xml形式等。

package com.search.pojo;

import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.annotation.JsonInclude;

import javax.xml.bind.annotation.XmlRootElement;

//@JsonInclude(JsonInclude.Include.NON_NULL)//不包含有null值的字段,即字段值为null的转换为json字符串时会被省略

@XmlRootElement(name=“MyJSONObject”)

public class MyJSONObject {

JSONObject jsonObject;

public JSONObject getJsonObject() {

    return jsonObject;

}

public void setJsonObject(JSONObject jsonObject) {

    this.jsonObject = jsonObject;

}

}
3:在实现类中,返回对象变为 pojo

   MyJSONObject myJSONObject=new MyJSONObject();

    myJSONObject.setJsonObject(jsonObject);

    return myJSONObject;

4:接口 方法 返回 也变为 pojo

@Path("/searchProductByText")

@GET

@Produces({"application/xml", "application/json"})

MyJSONObject productSearch(@QueryParam("text") String text);

5 可以返回值了。

6:前端接到响应体中的xml,可以转化为json

        httpResponse = httpUtil.HttpGet(requestParamMap, url);

        HttpEntity entity = httpResponse.getEntity();

        String s = EntityUtils.toString(entity);

        //将返回的xml字符串形式转化为json格式

        org.json.JSONObject xmlJSONObj = XML.toJSONObject(s);

        jsonObject = (JSONObject) JSON.parse(xmlJSONObj.toString());
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值