Spring Boot,如何从json文件读取特定对象,我需要什么注释?

时间:2018-10-22 13:33:06

标签: java json spring spring-boot web

我正在研究Spring Boot,我知道如何从资源目录读取JSON文件,但是我想获取特定数据,而不是整个数据。 像localhost:8080 / user返回用户名。

下面是我当前的代码

package com.example;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;



@RestController
@EnableAutoConfiguration
public class HelloWorld {

    @Value("classpath:json/test.json")
    private Resource resourceFile;
    @RequestMapping("/")
    Resource home() {
        return resourceFile;
    }


    public static void main(String[] args) throws Exception {
        SpringApplication.run(HelloWorld.class, args);
    }
}

我想读取test.json文件中的特定数据。请给我一些建议或步骤。谢谢

2 个答案:

答案 0 :(得分:0)

一如既往,有几种可能的方法。

除了手动解析和提取方法(How do I load a resource and use its contents as a string in Spring)外,您还可以尝试更高级的方法,并使用jackson-databind(https://github.com/FasterXML/jackson-databind)之类的库。

在您的资源中假定此json对象:

{
  "foo" : {
    "bar" : 42
  }
}

并且已经注入了Jackson ObjectMapper:

@Autowired
private ObjectMapper objectMapper;

选项1:对JsonNode使用通用方法

    @Autowired
    ObjectMapper objectMapper;

    @RequestMapping("/")
    JsonNode home() throws IOException {
        JsonNode jsonNode = objectMapper.readTree(resourceFile.getFile());
        return jsonNode.get("foo").get("bar");
    }

选项2:https://github.com/FasterXML/jackson-databind#1-minute-tutorial-pojos-to-json-and-back

答案 1 :(得分:0)

这只是@ibexit答案的变体,带有一些建议。

  1. 在ibexit答案中使用选项2(使用pojo),除非您确实需要JsonNode (您需要JsonNode的可能性四舍五入为0%。)
  2. 创建一个POJO来将您的Json表示为一个对象。 参见下面的示例。
  3. 我建议您使用@JsonIgnoreProperties(ignoreUnknown = true)批注。 进行Google搜索。
  4. 在您的示例中, 不需要使用@JsonProperty注释, 但我喜欢使用它。

还有其他方法可以设置“ ignoreUnknown”值, 杰克逊(Jackson)文档是一本好书,很有价值。

示例POJO

@JsonIgnoreProperties(ignoreUnknown = true)
public class TopClass
{
    @JsonProperty("foo") // This is optional in your example.
    private Foo foo;
}


@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo
{
    @JsonProperty("bar")
    private int bar;
}

读取POJO的示例代码

private TopClass topClassVariableName;

topClassVariableName = objectMapper.readValue(JSON HERE, TopClass.class);