Home > OS >  how to convert{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00} to json object
how to convert{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00} to json object

Time:05-07

myString = {AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};

i want to convert it by following {"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};

how can i do in java?

CodePudding user response:

You can JSONObject.. see below example

JSONObject main = new JSONObject();
main.put("Command", "CreateNewUser");
JSONObject user = new JSONObject();
user.put("FirstName", "John");
user.put("LastName", "Reese");
main.put("User", user);

For Json Data:

{
    "User": {
        "FirstName": "John",
        "LastName": "Reese"
    },
    "Command": "CreateNewUser"
}

CodePudding user response:

Without any libraries here's a solution.

public static void main(String[] args) {

        // Your String
        String value = "{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00}";
        value = value.replaceAll("[{}]", " ");
        String[] keyValuePairs = value.split(",");
        Map<String, String> map = new HashMap<>();

        for (String pair : keyValuePairs) {
            String[] entry = pair.split("=");
            map.put(entry[0].trim(), entry[1].trim());
        }
        // Create json String
        String json = "{"
                  map.entrySet().stream().map(e -> "\""   e.getKey()   "\":\""   String.valueOf(e.getValue())   "\"")
                        .collect(Collectors.joining(", "))
                  "}";
        System.out.println(json);

    }
  • Related