jackson string to json code example

Example 1: jackson create object node from string

@Testpublic 
void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect()   throws JsonParseException, IOException {
  String jsonString = "{"k1":"v1","k2":"v2"}";    
  ObjectMapper mapper = new ObjectMapper();
  
  JsonNode actualObj = mapper.readTree(jsonString);  
  JsonNode jsonNode1 = actualObj.get("k1");
  
  assertThat(jsonNode1.textValue(), equalTo("v1"));
}

Example 2: jackson create object node from string

@Testpublic void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect()   throws JsonParseException, IOException {    String jsonString = "{"k1":"v1","k2":"v2"}";    ObjectMapper mapper = new ObjectMapper();    JsonNode actualObj = mapper.readTree(jsonString);     // When    JsonNode jsonNode1 = actualObj.get("k1");    assertThat(jsonNode1.textValue(), equalTo("v1"));}

Example 3: convert json to object jackson

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
    "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

try {
    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println("car brand = " + car.getBrand());
    System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
    e.printStackTrace();
}

Example 4: jackson object to json

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValueAsString(car);

Example 5: jackson object to json

val objectMapper = ObjectMapper()
val car = Car("yellow", "renault")
objectMapper.writeValueAsString(car)

Tags:

Java Example