All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.zeebe.test.util.JsonUtil Maven / Gradle / Ivy

There is a newer version: 0.16.4
Show newest version
/*
 * Copyright © 2017 camunda services GmbH ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.zeebe.test.util;

import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;

public class JsonUtil {

  static final TypeReference> MAP_TYPE_REFERENCE =
      new TypeReference>() {};

  static final ObjectMapper JSON_MAPPER = new ObjectMapper();

  static {
    JSON_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
  }

  public static void assertEquality(String actualJson, String expectedJson) {
    try {
      assertThat(JSON_MAPPER.readTree(actualJson)).isEqualTo(JSON_MAPPER.readTree(expectedJson));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static JsonNode asJsonNode(String json) {
    try {
      return JSON_MAPPER.readTree(json);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static Map fromJsonAsMap(String json) {
    try {
      return JSON_MAPPER.readValue(json, MAP_TYPE_REFERENCE);
    } catch (IOException e) {
      throw new AssertionError(
          String.format("Failed to deserialize json '%s' to 'Map'", json), e);
    }
  }

  public static String toJson(Object o) {
    try {
      return JSON_MAPPER.writeValueAsString(o);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy