简体   繁体   中英

Add byte array inside a json object using java

I have below situation. It needs to be implemented in Java.

  1. Take input from a text file, convert the content into a byte array.
  2. Use the above byte array as a part of a JSON object , create a .json file

For point1, i have done something like this.

  InputStream is = new ClassPathresource("file.txt").getInputStream();
  byte[] ip =  IOUtils.toByteArray(is);

For point2, my Json file (containing json object), should look like below.

  {
   "name": "xyz",
   "address: "address here",
   "ipdata": ""
  }

The ipdata should contain the byte array created in step 1.

How can i create a json object with the byte array created in step 1 as a part of it ? And then write the entire content to a separate .json file ?

Also is the byte array conversion done in step1 an optimum way, or do we need to use any other API(may be to take care of encoding)?Please suggest.

Any help is appreciated. Thanks in advance.

  1. You can simply convert the byte array ip using ip.toString()
  2. Or if you know the encoding you can use ipString = new String(ip, "UTF8")

And then take that string to add to your json object.

Since you are reading a JSON string from file and want to write it back to a new json file you dont need the JSON Object conversion in-between. Just convert the byte[] to String as

String ips = new String(ip);

Now create a JSON Object with the data you want to write to the new file. And then you can write the data to file using FileWriter . PFB the code-

JSONObject obj = new JSONObject();
obj.put("name", "xyz");
obj.put("address", "address here");
obj.put("ipdata", ips);
try(FileWriter fileWriter =
    new FileWriter("newFileName.json") ){
    fileWriter.write(obj.toString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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