MG.
MG.

Reputation: 25

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?

Upvotes: 0

Views: 2373

Answers (2)

rasfarrf5
rasfarrf5

Reputation: 237

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 :)

Upvotes: 1

Dayakar Akula
Dayakar Akula

Reputation: 133

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

Upvotes: 0

Related Questions