使用Jersey

时间:2016-03-24 05:23:51

标签: java json jersey

我正在向我的Web服务发送一个JSON对象,该服务也有内部JSON对象。我无法在我的网络服务中获取它。我的客户端代码如下

var courseDetails = '{"UserId": "abc","CourseId": "C1","CourseDetails":{"Id": "_26_1","Name": "Group task test (revised)","Description": "Sample Description"}}';
    var obj = JSON.parse(courseDetails);    
    $http({
        method: 'POST',         
        url: 'rest/DB/Save',
        headers: {'Content-Type': 'application/json'},
        data : courseDetails,
        }).success(function (data){
            $scope.status=data;
        }).error(function(data, status, headers, config) {
            alert("error");
       });

并在我的网络服务中

    @POST
@Path("/Save")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.TEXT_PLAIN})
public String  autoSave(JSONObject obj) throws Exception{

    PersonalisationDao p = new PersonalisationImpl();
    System.out.println("Obj "+obj);
    String result = "failure";
    if(obj != null) {
        String userId = (String) obj.get("UserId");
        String courseId = (String) obj.get("CourseId");         
        String courseDetails =  (String) obj.get("CourseDetails");
        // Problem in fetching course Details 
        result = p.addDetails(userId, courseId, courseDetails);    
    }
    return result;
}

通常它应该是一个JSON对象,但它抛出

SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.String

我也尝试过使用JSONObject进行投射,但它仍然没有用。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

最初通过强制转换为LinkedHashMap,然后最终转换为字符串。

LinkedHashMap courseDetails =  (LinkedHashMap) obj.get("CourseDetails");
String jsonCourseString = new Gson().toJson(courseDetails, Map.class);