-7

I am new to creating files. I need to create JSON that I will import into my firewall. I created two test rules so that I could export the format of the file I will need to create for import. The final output will need to look like this:

[
    {
        "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
    }
]

I have a text file that contains all of the IP's I want insert into the file. The Description will be a static description.

The text file IP's are listed one per line like:

1.2.3.4  
1.2.3.5

I'm pretty new at programming I've used Java and VB before but have never had to read a file, insert that record into a new string in a new file, and then do the next record. If another language would be easier I will learn whatever I need to. This is something that I will be using for other projects after I get the hang of it.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
c3rb3rus
  • 1
  • 2

1 Answers1

1

Give it a try it will work, It uses JSONSimple library to prepare the JSON Data

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();
    }

}
}
Rishal
  • 1,480
  • 1
  • 11
  • 19