001package ca.uhn.fhir.util; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2020 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import com.fasterxml.jackson.annotation.JsonInclude; 024import com.fasterxml.jackson.databind.ObjectMapper; 025import com.fasterxml.jackson.databind.SerializationFeature; 026 027import javax.annotation.Nonnull; 028import java.io.IOException; 029import java.io.StringWriter; 030import java.io.Writer; 031 032public class JsonUtil { 033 034 private static final ObjectMapper ourMapperPrettyPrint; 035 private static final ObjectMapper ourMapperNonPrettyPrint; 036 037 static { 038 ourMapperPrettyPrint = new ObjectMapper(); 039 ourMapperPrettyPrint.setSerializationInclusion(JsonInclude.Include.NON_NULL); 040 ourMapperPrettyPrint.enable(SerializationFeature.INDENT_OUTPUT); 041 042 ourMapperNonPrettyPrint = new ObjectMapper(); 043 ourMapperNonPrettyPrint.setSerializationInclusion(JsonInclude.Include.NON_NULL); 044 ourMapperNonPrettyPrint.disable(SerializationFeature.INDENT_OUTPUT); 045 } 046 047 /** 048 * Parse JSON 049 */ 050 public static <T> T deserialize(@Nonnull String theInput, @Nonnull Class<T> theType) throws IOException { 051 return ourMapperPrettyPrint.readerFor(theType).readValue(theInput); 052 } 053 054 /** 055 * Encode JSON 056 */ 057 public static String serialize(@Nonnull Object theInput) throws IOException { 058 return serialize(theInput, true); 059 } 060 061 /** 062 * Encode JSON 063 */ 064 public static String serialize(@Nonnull Object theInput, boolean thePrettyPrint) throws IOException { 065 StringWriter sw = new StringWriter(); 066 if (thePrettyPrint) { 067 ourMapperPrettyPrint.writeValue(sw, theInput); 068 } else { 069 ourMapperNonPrettyPrint.writeValue(sw, theInput); 070 } 071 return sw.toString(); 072 } 073 074 /** 075 * Encode JSON 076 */ 077 public static void serialize(@Nonnull Object theInput, @Nonnull Writer theWriter) throws IOException { 078 // Note: We append a string here rather than just having ourMapper write directly 079 // to the Writer because ourMapper seems to close the writer for some stupid 080 // reason.. There's probably a way of preventing that bit I'm not sure what that 081 // is and it's not a big deal here. 082 theWriter.append(serialize(theInput)); 083 } 084 085}