Java String to JSON conversion

后端 未结 4 916
遇见更好的自我
遇见更好的自我 2021-01-01 16:23

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :

4条回答
  •  借酒劲吻你
    2021-01-01 17:19

    Converting the String to JsonNode using ObjectMapper object :

    ObjectMapper mapper = new ObjectMapper();
    
    // For text string
    JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)
    
    // For Array String
    JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)
    
    // For Json String 
    String json = "{\"id\" : \"1\"}";
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser jsonParser = factory.createParser(json);
    JsonNode node = mapper.readTree(jsonParser);
    

提交回复
热议问题