简体   繁体   English

通过使用SpringBoot读取属性文件来生成JSON结构

[英]Produce a JSON structure by reading a property file using SpringBoot

I'm writing a method in SpringBoot which reads the property file and produce JSON through endpoints. 我正在SpringBoot中编写一个方法,该方法读取属性文件并通过端点生成JSON。 My property file looks like this: 我的属性文件如下所示:

Category.1=Quality=A,B,C,D
Category.2=Program=E,F,G
Category.3=Efficiency=H,I,J,K

I need to read only the values which is starting from Category ,my property file may contain other data. 我只需要读取从Category开始的值,我的属性文件可能包含其他数据。 The JSON should look like this: JSON应该如下所示:

{
"Quality":[
  "A",
  "B",
  "C",
  "D"
],
"Program":[
  "E",
  "F",
  "G"
],
"Efficiency":[
  "H",
  "I",
  "J",
  "K"
]
}

I need to create a REST endpoints to get this JSON value. 我需要创建一个REST端点来获取此JSON值。 I know how to read the property file and get the values. 我知道如何读取属性文件并获取值。 As this property file is bit complex to me I need to get Quality , Program and efficiency as the key and remaining as it's value. 由于此属性文件对我来说有点复杂,因此我需要将Quality,Program和Efficiency作为关键,并保留其价值。 I'm new to programming please help me out. 我是编程新手,请帮帮我。

Use a library such as jackson to create the json. 使用诸如jackson之类的库来创建json。 A working example with the properties you specified is here. 具有您指定的属性的工作示例在此处。 A few basic steps: 一些基本步骤:

  1. Get the properties 获取属性
  2. Create an empty json object node 创建一个空的json对象节点
  3. Iterate over the properties, getting the ones you need (that have keys starting with "Category" in your case) 遍历属性,获取所需的属性(在您的情况下,其键以“ Category”开头)
  4. Split each valid property value on the = to break it into the json key you want and the csv list of categories =上拆分每个有效属性值,将其分为所需的json键和类别的csv列表
  5. Create a json array out of each list in (4) 从(4)中的每个列表创建一个json数组
  6. Add this array to the node in (2) with the key in (4) 使用(4)中的键将此数组添加到(2)中的节点

Add the dependencies 添加依赖项

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.4'

to your project for the example to work. 到您的项目中以使示例工作。

public static void main(String... args) throws IOException {
    Properties p = new Properties();
    p.load(Test.class.getResourceAsStream("/myfile.properties"));

    ObjectNode node = JsonNodeFactory.instance.objectNode();

    String prefix = "Category.";
    String delimiter = ",";

    p.forEach((k, v) -> {
        String propKey = k.toString();
        if (propKey.startsWith(prefix)) {
            String[] propVal = v.toString().split("=");
            ArrayNode array = JsonNodeFactory.instance.arrayNode();
            for (String arrVal : propVal[1].split(delimiter)) {
                array.add(arrVal);
            }
            node.set(propVal[0], array);
        }
    });

    System.out.println(node);
}

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

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