【问题标题】:Create a json file with both static data and a dynamic list of IP's创建一个包含静态数据和动态 IP 列表的 json 文件
【发布时间】:2017-01-08 07:40:00
【问题描述】:

我是创建文件的新手。我需要创建将导入防火墙的 JSON。我创建了两个测试规则,以便可以导出我需要为导入创建的文件的格式。最终输出需要如下所示:

[
    {
        "id" : 1,
        "enabled" : true,
        "category" : null,
        "readOnly" : null,
        "description" : "Test Rule #1",
        "string" : "1.2.3.4",
        "name" : null,
        "flagged" : true,
        "javaClass" : "com.testServer.uvm.node.GenericRule",
        "blocked" : true
    }, {
        "id" : 2,
        "enabled" : true,
        "category" : null,
        "readOnly" : null,
        "description" : "Test Rule #2",
        "string" : "1.2.3.5",
        "name" : null,
        "flagged" : true,
        "javaClass" : "com.testServer.uvm.node.GenericRule",
        "blocked" : true
    }
]

我有一个文本文件,其中包含我想要插入到文件中的所有 IP。描述将是静态描述。

文本文件 IP 每行列出一个,例如:

1.2.3.4  
1.2.3.5

我对编程很陌生,我以前使用过 Java 和 VB,但从来没有读取文件,将该记录插入新文件中的新字符串,然后执行下一条记录。如果另一种语言会更容易,我会学习我需要的任何东西。这是我掌握它的窍门后将用于其他项目的东西。

【问题讨论】:

  • 您可能在这里问这个问题太早了,因为您没有向我们展示您自己解决此问题的尝试,也没有描述您在此尝试中可能遇到的问题。
  • 您是否研究过之前的类似问题并尝试实施他们的解决方案?如果我站在你的立场上,这是我要做的第一件事。

标签: java json file programmatically-created


【解决方案1】:

试一试,它会工作,它使用 JSONSimple 库来准备 JSON 数据

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Test {
public static void main(String[] args) throws IOException {
    // file name from where you read the urls
    List<String> url = Files.readAllLines(Paths.get("url.txt"));
    //List to hold the contents and prepare json data
    JSONArray list = new JSONArray();

    try {

        FileWriter file = new FileWriter("test.json");

        for (int i = 0; i < url.size(); i++) {
            JSONObject obj = new JSONObject();
            obj.put("id", i+ 1);
            obj.put("enabled", new Boolean(true));
            obj.put("category", null);
            obj.put("readOnly", null);
            obj.put("description", new String("Test Rule #" + (i + 1)));
            obj.put("string", url.get(i));
            obj.put("name", null);
            obj.put("flagged", new Boolean(true));
            obj.put("javaClass", new String("com.testServer.uvm.node.GenericRule"));
            obj.put("blocked", new Boolean(true));
            list.add(obj);
        }
        file.write(list.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2018-02-26
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多