首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何正确返回JsonObject?

如何正确返回JsonObject?
EN

Stack Overflow用户
提问于 2018-07-24 05:06:50
回答 1查看 0关注 0票数 0

我正在尝试使JsonRPC-API与Springboot一起使用。

我正在使用briandilley / jsonrpc4j库。

我创建了一个ApplicationConfig类,并通过@JsonRpcService(“/ path”)注释绑定到Inteface,如下所示。

ApplicationConfig.class

代码语言:javascript
复制
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {

    @Bean
    public static AutoJsonRpcServiceImplExporter autoJsonRpcServiceImplExporter() {
        AutoJsonRpcServiceImplExporter exp = new AutoJsonRpcServiceImplExporter();
        //in here you can provide custom HTTP status code providers etc. eg:
        //exp.setHttpStatusCodeProvider();
        //exp.setErrorResolver();
        return exp;
    }
}

API接口

代码语言:javascript
复制
import com.googlecode.jsonrpc4j.JsonRpcParam;
import com.googlecode.jsonrpc4j.JsonRpcService;

import java.util.ArrayList;

@JsonRpcService("/api/test")
public interface testApi {
    JsonObject test();
}

这是我实现接口以执行实际逻辑并返回JsonObject的类。

testApiImpl.class

代码语言:javascript
复制
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.JsonObject;
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@AutoJsonRpcServiceImpl
public class testApiImpl implements testApi {
    @Override
    public JsonObject test() {
        JsonObject obj = new JsonObject();
        obj.addProperty("id", "0");
        obj.addProperty("name", "rachael");
        obj.addProperty("age", "27");
        return obj;
    }
}

这是一个简单的测试,用于检查jsonObject是否实际正确返回。我只是创建了一个JsonObject并返回它。也许我认为这太简单了。

代码语言:javascript
复制
curl -sH "Content-Type:application/json" -d '{"id":"1","jsonrpc":"2.0","method":"test","params":{}}' http://localhost:8080/api/test

当我通过Curl调用方法时,我收到了这样的错误。

{"jsonrpc":"2.0","id":"1","error":{"code":-32001,"message":"JsonObject (through reference chain: com.google.gson.JsonObject[\"asLong\"])","data":{"exceptionTypeName":"java.lang.IllegalArgumentException","message":"JsonObject (through reference chain: com.google.gson.JsonObject[\"asLong\"])"}}}

我是Java和SpringBoot的新手,所以我确信还有另一种方法可以返回JsonObject并设置错误代码和消息。如何设置状态代码(即错误代码)和消息并成功返回JsonObject?

EN

回答 1

Stack Overflow用户

发布于 2018-07-24 14:09:11

如果你尝试使用这个包对象,它应该工作正常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档