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?

2 answers

  • answered 2022-05-07 05:34 Daya A L

    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"

  • answered 2022-05-07 07:16 rasfarrf5

    You can use Gson to convert key value String to Object. For Eg,

    // You Model:
    Class MyModel {
      String AcquirerName;
      double AcquiringBankCode;
      int ApprovalCode;
    // Impl
    Gson gson = new Gson();
    String myString = "{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00}";
    MyModel myModel = gson.fromJson(json, MyModel.class); 
    // You can access myModel.AcquirerName
    // Gson Dependency

    Hope it helps :)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum