简体   繁体   中英

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.

There can be multiple fields like amountValue in the json. I am looking for a generic way which can parse json with any number of such attributes value to string. My request will have around 200 fields.

ex: "amountValue": 200.00, to "amountValue": "200.00",

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

My mongoDB Document is of the form

    @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.

In my controller, converting the request object to 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:

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"}}}

Is there any way to accomplish the result? Or anything which can help to store documents in mongodb with attribute type as String?

You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng.

If your Json structure won't change and will remain as said above, you can do the following.

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

{"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:

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. This way they will be interpreted as strings when the json willl be parsed.

It will not work if the value is in an array though, but in this case it should not be a problem.

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