Home > Enterprise >  Reading values from JSON file with exact decimal points with Java
Reading values from JSON file with exact decimal points with Java

Time:06-01

I have a json file as below.

   {
    "name": "Smith",
    "Weight": 42.000,
    "Height": 160.050 
   }

I have written the following java code to read this file.

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;

public class TestFileReaderApplication {

    public static void main(String[] args) {
        readFile();
    }


    public static void readFile()  {
        JSONParser jsonParser = new JSONParser();
        JSONObject requestBody = null;
        try(FileReader reader = new FileReader("C:\\Users\\b\\Desktop\\test.json")){
            requestBody = (JSONObject) jsonParser.parse(reader);
            System.out.println(requestBody);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

Output shows as follow:

{"name":"Smith","Height":160.05,"Weight":42.0}

When I debug the program JSON reads 160.050 as 160.05 and 42.000 as 42.0

Text

I need Weight and Height values decimal points as it is. The number of decimal points can be changed. How can I read a json file as a JSONObject with the given decimal points?

CodePudding user response:

A solution would be to use Gson and JsonObject

import com.google.gson.Gson;
import com.google.gson.JsonObject;

try(FileReader reader = new FileReader("C:\\Users\\b\\Desktop\\test.json")){
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
            System.out.println(jsonObject);
        } catch (IOException e) {
        e.printStackTrace();
    }

the Output

{"name":"Smith","Weight":42.000,"Height":160.050}
  • Related