user2094311
user2094311

Reputation:

Add Json file contents to JsonObject in Java

I have a Json file E:\\jsondemo.json in disk. I want to create JSONObject in Java and add the contents of the json file to JSONObject. How it is possible?

JSONObject jsonObject = new JSONObject();

After creating this objec, what should i do to read the file and put values in jsonObject Thanks.

Upvotes: 0

Views: 2885

Answers (1)

Vito Gentile
Vito Gentile

Reputation: 14426

You can transform a file in a String using a function proposed in this question:

private static String readFile(String path) throws IOException {
  FileInputStream stream = new FileInputStream(new File(path));
  try {
    FileChannel fc = stream.getChannel();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    /* Instead of using default, pass in a decoder. */
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}

After getting the string, you can transform it to a JSONObject with the following code:

String json = readFile("E:\\jsondemo.json");
JSONObject jo = null;
try {
jo = new JSONObject(json);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

In the above example, I used this library, very simple to learn. You can add values to your JSON object in this way:

jo.put("one", 1); 
jo.put("two", 2); 
jo.put("three", 3);

You can also create JSONArray objects, and add it to your JSONObject:

JSONArray ja = new JSONArray();

ja.put("1");
ja.put("2");
ja.put("3");

jo.put("myArray", ja);

Upvotes: 0

Related Questions