Home > Net >  How to convert String having key=value pairs to Json
How to convert String having key=value pairs to Json

Time:05-07

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?

CodePudding user response:

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
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Hope it helps :)

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