vikas
vikas

Reputation: 73

Unable to Convert String into JSON using Java

I am getting a json from rest call as {"d1":1, "d2":1, "d3":0, "d4":1} which is stored in db as - {d1=1, d2=1, d3=0, d4=1}.

When I am reading from database i am getting the above as string as - {d1=1, d2=1, d3=0, d4=1}. I want to convert this to its original form as before like - {"d1":1, "d2":1, "d3":0, "d4":1} mentioned above.

How can i achieve this in java. is there any json library available to do this ?

Sofar I have tried this but it didn't worked out -

JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(jsonString);

I want to put this json in ResponseEntity>.

Even I tried -

jsonString = jsonString.replaceAll("=", ":"); JSONObject jsonObject = new JSONObject(jsonString);

String finalJsonString = jsonObject.toString();

This is giving back response as "{\"d1\":1, \"d2\":1, \"d3\":0, \"d4\":1}" with double quotes in the begining and ending with backslashes before double quotes for keys.

Upvotes: 0

Views: 1586

Answers (3)

user11425844
user11425844

Reputation:

You can do as follows :

ObjectMapper mapper = new ObjectMapper();
            try {
                MyResponse result = mapper.readValue(e.getResponseBodyAsString(),MyResponse.class);
                return result;
            } catch (IOException e1) {
                e1.printStackTrace();
            }

Upvotes: 0

DEBENDRA DHINDA
DEBENDRA DHINDA

Reputation: 1193

The string that you are retrieving from DB is a Map data structure. So you can convert a Map to JSON as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);

Edited

The following code snippet will provide you the complete JSON response.

@RestController
@RequestMapping("/api/v1/")
public class TestController {

@GetMapping(value="test",produces=MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<String> test() {

        Map<String,String> payload = new HashMap<>();
        payload.put("d1","value1");
        payload.put("d2","value2");
        payload.put("d3","value3");
        payload.put("d4","value4");
        String json =null;
        try {
             json= new ObjectMapper().writeValueAsString(payload);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }       
        return new ResponseEntity(json,HttpStatus.OK);
    }
}

Postman test: Postman Test

Upvotes: 0

Pavithra Gunasekara
Pavithra Gunasekara

Reputation: 4112

The String returned through DB is not in JSON format, so parsing fails.

You could use the following approach to format the returned string into a JSON string, and then parse it. I have used Guava's Splitter.MapSplitter:

        String in = "{d1=1,d2=1,d3=0,d4=1}";
        in = in.replaceAll("[{}]", "");
        Map<String, String> properties = Splitter.on(",").withKeyValueSeparator("=").split(in);
        JSONObject obj = new JSONObject(properties);
        String formattedString = obj.toString();

Upvotes: 0

Related Questions