'How to convert String having key=value pairs to Json

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

I want to convert it to the following string.

{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};

How can I do it in java?



Solution 1:[1]

You can use Gson to convert the key-value String to Object and convert it into JSON. For Eg,

Add the following dependency:

<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>

Your Model:

class MyModel {
    String AcquirerName;
    double AcquiringBankCode;
    int ApprovalCode;
//getter //setter //constructor
}

Verify:

public static void main(String[] args) {

        // Impl
        Gson gson = new Gson();
        String myString = "{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00}";
        MyModel myModel = gson.fromJson(myString, MyModel.class);
        String json = gson.toJson(myModel, MyModel.class);
        System.out.println(json);
    }

O/P: {"AcquirerName":"abc","AcquiringBankCode":0.2,"ApprovalCode":0}

Hope it helps :)

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sibin Rasiya
Solution 2 Daya A L