简体   繁体   English

使用 Java 从 JSON 文件中读取具有精确小数点的值

[英]Reading values from JSON file with exact decimal points with Java

I have a json file as below.我有一个如下的 json 文件。

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

I have written the following java code to read this file.我编写了以下 java 代码来读取此文件。

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当我调试程序 JSON 读取 160.050 为 160.05 和 42.000 为 42.0

文本

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?如何将 json 文件读取为具有给定小数点的 JSONObject?

A solution would be to use Gson and JsonObject一个解决方案是使用GsonJsonObject

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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