简体   繁体   English

如何将每个整数/双精度值从包含嵌套对象和 arrays 的 JSON 数据转换为字符串?

[英]How can I convert each integer/double value to String from JSON data containing nested objects and arrays?

I want to convert each integer/double value to String present in json request before storing in MongoDB database.在存储到 MongoDB 数据库之前,我想将每个整数/双精度值转换为 json 请求中存在的字符串。

There can be multiple fields like amountValue in the json. json 中可以有多个字段,如 amountValue。 I am looking for a generic way which can parse json with any number of such attributes value to string.我正在寻找一种通用方法,它可以将 json 与任意数量的此类属性值解析为字符串。 My request will have around 200 fields.我的请求将包含大约 200 个字段。

ex: "amountValue": 200.00, to "amountValue": "200.00",例如:“amountValue”:200.00,到“amountValue”:“200.00”,

{
    
    "templateName": "My DC Template 14",
    "templateDetails": {
        
        "beneficiaryName": "Snow2",
        "dcOpenAmount": {
            "amountValue": 200.00,
            
        }
    }
}

My mongoDB Document is of the form我的 mongoDB 文档的格式为

    @Document
    
    public class TemplateDetails  {
    
        @Id
        private long templateId;
        private String templateName;
        private Object  templateDetail;
    }

Because we are storing document in mongodb as an object (Which can accept any type of json request) we dont have field level control on it.因为我们将文档作为object存储在 mongodb 中(可以接受任何类型的 json 请求),所以我们没有对其进行字段级别控制。

In my controller, converting the request object to json.在我的 controller 中,将请求 object 转换为 json。 This is how I tried.这就是我尝试的方式。 But its not meeting my expectation.但它没有达到我的期望。 It is still keeping the amount value to its original double form.:它仍将金额值保持为其原始的双精度形式。:

    ObjectMapper mapper = new ObjectMapper();
            try {
              String json = mapper.writeValueAsString(templateRequestVO);
              System.out.println("ResultingJSONstring = " + json);
             
            } catch (JsonProcessingException e) {
               e.printStackTrace();
            }

Output: Output:

ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"My DC Template 14","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE","state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2","dcOpenAmount": {"amountValue":200.0 ,"currency":"USD"}}} ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"我的 DC 模板 14 ","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE", "state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2", "dcOpenAmount": {"amountValue":200.0 ,"currency":"USD"}}}

Is there any way to accomplish the result?有什么办法可以实现结果吗? Or anything which can help to store documents in mongodb with attribute type as String?或者任何可以帮助将文档存储在 mongodb 中且属性类型为字符串的东西?

You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng.您可以使用“org.json.JSONObject”中可用的 Json 操作将 Double 值转换为 Stirng。

If your Json structure won't change and will remain as said above, you can do the following.如果您的 Json 结构不会改变并保持如上所述,您可以执行以下操作。

import org.json.JSONObject;

public static void main(String args[]) {
        String j = "{ \"templateName\": \"My DC Template 14\", \"templateDetails\": { \"beneficiaryName\": \"Snow2\", \"dcOpenAmount\": { \"amountValue\": 200.00 } } }";


        JSONObject jo = new JSONObject(j);

        jo.getJSONObject("templateDetails")
        .getJSONObject("dcOpenAmount")
        .put("amountValue", String.valueOf(jo.getJSONObject("templateDetails").getJSONObject("dcOpenAmount").getDouble("amountValue")));
        
        System.out.println(jo.toString());
    }


Following will be the output以下是 output

{"templateDetails":{"dcOpenAmount":{"amountValue":"200.0"},"beneficiaryName":"Snow2"},"templateName":"My DC Template 14"}

I don't know for mongodb but for a json string you can replace them with a regex and the function replace like this:我不知道 mongodb 但对于 json 字符串,您可以用正则表达式替换它们,而 function 替换如下:

public class Test {
     public static void main(String[] args) {
        String json = "{\"id\":null,\"userId\":\"FU.ZONKO\",\"txnType\":\"LCI\",\"accessIndicator\":\"Public\",\"templateId\":null,\"templateName\":\"My DC Template 14\",\"tags\":null,\"templateDetails\":{\"applicantDetail\":{\"applicantName\":\"Tom\",\"applicantAddress\":{\"addressLine1\":\"Infosys, Phase 2\",\"city\":\"PUNE\",\"state\":\"MAHARASHTRA\",\"country\":\"INDIA\",\"zip\":\"40039\"},\"accountId\":\"Account1234\",\"customerId\":\"JPMORGAN\"},\"beneficiaryName\":\"Snow2\",\"dcOpenAmount\":{\"amountValue\":200.0,\"currency\":\"USD\"}}}";
        System.out.println(replaceNumberByStrings(json));
    }
    public static String replaceNumberByStrings(String str){
        return str.replaceAll("(?<=:)\\d+(\\.\\d+)?(?=(,|}))","\"$0\"");
    }
}

It will look for all fields with a numeric value in the json string and add quotes to the value.它将在 json 字符串中查找所有具有数值的字段,并为该值添加引号。 This way they will be interpreted as strings when the json willl be parsed.这样,当 json 将被解析时,它们将被解释为字符串。

It will not work if the value is in an array though, but in this case it should not be a problem.如果值在数组中,它将不起作用,但在这种情况下,它应该不是问题。

暂无
暂无

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

相关问题 如何在Java脚本中将Json数组从字符串转换为整数 - How to convert Json arrays to integer from string in Java script 如何将对象值转换为包含对象中多个数据的字符串? - How to convert object value into string containing multiple data in objects? 使用Regex进行数据处理时如何将数据从字符串转换为整数 - How can I convert data to integer from string when I have data using Regex 我有一个包含多个 JSON 对象的数据字符串,如何将字符串中的所有 JSON 对象存储在一个充满对象的数组中? - I have a data String with multiple JSON Objects, how can I store all JSON Objects from the String in an Array filled with objects? 如何将部分十六进制字符串转换为 Java 中的 Integer 值 - How I can convert a part of Hex String to Integer value in Java 如何从扫描仪获取多个整数输入并将每个整数存储在单独的数组中? - How can I take multiple integer input from scanner and store each integer in separate arrays? 如何对 HashMap 进行排序<String, Pair<Double, Integer> &gt; 双倍价值? - How can I sort a HashMap<String, Pair<Double, Integer>> by Double Value? 不正确的整数值:如何将我的数据从String转换为Int以避免Auto_Increment? - Incorrect Integer Value: How do i convert my Data from String to Int to avoid Auto_Increment? 是否可以将String转换为Integer或为其分配值? - Can I convert a String into Integer or assign it with a value? 如何使用Gson将JSON对象字符串转换为ArrayList? - How can I convert a JSON string of objects into an ArrayList using Gson?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM