无法使用Java将字符串转换为JSON

时间:2019-04-19 17:31:24

标签: java spring-boot

我从{{d1“:1,” d2“:1,” d3“:0,” d4“:1}的剩余调用中得到一个json,它以-{d1 = 1,d2 = 1,d3 = 0,d4 = 1}。

当我从数据库中读取数据时,我将上述内容作为字符串获取-{d1 = 1,d2 = 1,d3 = 0,d4 = 1}。我想像以前一样将其转换为原始格式,如上述-{“ d1”:1,“ d2”:1,“ d3”:0,“ d4”:1}。

如何在Java中实现这一目标。有没有可用于执行此操作的json库?

到目前为止,我已经尝试过了,但是没有成功-

JSONParser解析器=新的JSONParser(); JSONObject json =(JSONObject)parser.parse(jsonString);

我想将此json放入ResponseEntity>。

即使我尝试-

jsonString = jsonString.replaceAll(“ =”,“:”); JSONObject jsonObject =新的JSONObject(jsonString);

String finalJsonString = jsonObject.toString();

这将以“ {\” d1 \”:1,\“ d2 \”:1,\“ d3 \”:0,\“ d4 \”:1}”开头的开头给出双引号并在键的双引号之前以反斜杠结束。

3 个答案:

答案 0 :(得分:0)

通过数据库返回的字符串不是JSON格式,因此解析失败。

您可以使用以下方法将返回的字符串格式化为JSON字符串,然后对其进行解析。 我用过GuavaSplitter.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();

答案 1 :(得分:0)

您将从数据库中检索的字符串是Map数据结构。因此,您可以按以下方式将Map转换为JSON:

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

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

已编辑

以下代码段将为您提供完整的JSON响应。

@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

答案 2 :(得分:0)

您可以执行以下操作:

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