【问题标题】:JSON to POJO conversion errorJSON 到 POJO 转换错误
【发布时间】:2014-04-17 14:09:38
【问题描述】:

我正在尝试将 JSON 请求传递到我的服务器,其中控制器在将 JSON 转换为 POJO 时遇到错误。

JSON 请求

{ 
   "request":[
      {"name":"mac"},
      {"name":"rosy"}
   ]
}

我的控制器功能

@RequestMapping(value = "/namelist", 
            method = RequestMethod.POST,
            consumes = { "application/json" },
            produces = {"application/json"})
public ... postNameList(@RequestBody NameList names) {}


Public Class NameList extends ArrayList<Name> {}
Public Class Name { private name; ...}

错误

消息:“无法读取 JSON:无法反序列化 com.abc.xyz.mypackage.NameList out of START_OBJECT token at [Source: org.eclipse.jetty.server.HttpConnection$Input@79aac24b{HttpChannelOverHttp@1d109942{r=1,a=DISPATCHED,uri=/namelist},HttpConnection@2cbdcaf6{FILLING},g=HttpGenerator{s=START},p= HttpParser{s=END,137 137}};行:1,列:1]

我不确定代码有什么问题。我对 Spring 还很陌生,因此不胜感激。

【问题讨论】:

  • 您的 JSON 不是数组。它是一个具有单个字段的对象,其值为一个数组。
  • 你能给我举一个 JSON 是数组的例子吗?
  • 删除 JSON 中方括号前后的所有内容... Presto,您只有一个数组(并且您的代码可以工作)

标签: java json spring jackson pojo


【解决方案1】:

您的 POJO 类应如下所示:

class Request {
    private List<Name> request;

    // getters, setters, toString, ...
}

class Name {
    private String name;

    // getters, setters, toString, ...
}

用法:

@RequestMapping(value = "/namelist", 
            method = RequestMethod.POST,
            consumes = { "application/json" },
            produces = {"application/json"})
public ... postNameList(@RequestBody Request request) { ... }

【讨论】:

    【解决方案2】:

    我遇到了类似的情况,然后创建了将 JSON 对象转换为 Java 对象的实用程序。希望这会有所帮助。

    这里的sample.json是你想要的Java对象文件

    import com.sun.codemodel.JCodeModel;
    import org.jsonschema2pojo.*;
    import org.jsonschema2pojo.rules.RuleFactory;
    import org.springframework.util.ResourceUtils;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URL;
    
    /**
     * Created by Pratik Ambani
     */
    class JsonToPojo {
    
        public static void main(String[] args) {
            String packageName = "com.practise";
            File inputJson = null;
            try {
                inputJson = ResourceUtils.getFile("classpath:sample.json");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File outputPojoDirectory = new File("." + File.separator + "Generated Pojo");
            outputPojoDirectory.mkdirs();
    
            try {
                new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
            } catch (IOException e) {
                System.err.println("Encountered issue while converting to pojo: " + e.getMessage());
                e.printStackTrace();
            }
        }
    
        private void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException {
            JCodeModel codeModel = new JCodeModel();
            GenerationConfig config = new DefaultGenerationConfig() {
                @Override
                public boolean isGenerateBuilders() { // set config option by overriding method
                    return true;
                }
    
                @Override
                public SourceType getSourceType() {
                    return SourceType.JSON;
                }
            };
            SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
            mapper.generate(codeModel, className, packageName, inputJson);
            codeModel.build(outputPojoDirectory);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-04
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2021-10-17
      • 1970-01-01
      • 2019-07-06
      相关资源
      最近更新 更多