Convert a Byte Array to Json with Java

Json is an open standard file format which uses readable text to store and transfer data objects. In this tutorial we are looking at how we can convert a Byte Array in to a Json String with Java.

For this conversion we have used Jackson JSON processor for Java.

Add the library as below

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.3</version>
</dependency>

We are mainly using the ObjectMapper class in Jackson which provides functionality for reading and writing JSON.

is a feature that determines whether it is acceptable to coerce non-array(in JSON) values to handle with Java collection.

DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature can be used for compatibility/interoperability reasons,to work with different JSON converters(eg. XML to JSON)) and that leave out JSONarray in cases where there is just a single element in array.

	protected List<Map<?, ?>> convertToMap(byte[] data)
			throws JsonParseException, JsonMappingException, IOException {

		List<Map<?, ?>> dataList = null;

		ObjectMapper objMapper = new ObjectMapper();
		objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
		dataList = objMapper.readValue(data, new TypeReference<List<Map<?, ?>>>() {
		});

		return dataList;
	}

Leave a Reply

Your email address will not be published. Required fields are marked *