繁体   English   中英

如何正确返回JsonObject? | 带有SpringBoot的JsonRPC-API

[英]How to return JsonObject properly? | JsonRPC-API with SpringBoot

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

我正在使用briandilley / jsonrpc4j库。

链接: https : //github.com/briandilley/jsonrpc4j

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

ApplicationConfig.class

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接口

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

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并将其返回。 也许我认为这太简单了。

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?

杰克逊支持org.json.JSONObjectorg.json.JSONArray 因此,如果您尝试使用此包对象,它应该可以正常工作。 希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM