Home > Enterprise >  Convert Map to JSON in Java
Convert Map to JSON in Java

Time:10-15

I'm migrating from node to java and finding really difficult to work with JSON I have the following Map structure:

{1=Terrain, 2=Tree, 3=Building}

Which I need to transform into JSON, but with this strcutre:

[{ id: 1, name: Terrain }, { id: 2, name: Tree }, { id: 3, name: Building }]

How can I achieve that? Thanks

CodePudding user response:

The map in Java is the same as this object in Javascript:

var map = {};
map[1] = "Terrain";
map[2] = "Tree";

This will produce the same json.

Now to fix the issue in Java, you will need to convert the map to a list of objects:

Map<Integer, String> originalMap = //your map with values

List<Structure> mappedList = originalMap.entrySet()
        .stream()
        .map(entry -> new Structure(entry.getKey(), entry.getValue()))
        .collect(Collectors.toList());
//convert mappedList via jackson

Structure is just a class I created that matches the properties id and name from the json:

public class Structure {
    private int id;
    private String name;

    public Structure(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

CodePudding user response:

Multiple APIs available for Map to JSON converter

  1. Using Jackson API
  2. Using Gson API
  3. Using org.json API

For Jackson API

For that you need to add jakson dependencies in project

<dependencies>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
</dependencies>

Please look into following Main program for conversation

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;

public class ConvertJavaMapToJson {

@Test
public void convertMapToJson() {
    Map<String, String> elements = new HashMap();
    elements.put("Key1", "Value1");
    elements.put("Key2", "Value2");
    elements.put("Key3", "Value3");

    ObjectMapper objectMapper = new ObjectMapper();

    try {
        String json = objectMapper.writeValueAsString(elements);
        System.out.println(json);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
  }
}

For Gson

<dependencies>
   <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
   </dependency>
</dependencies>


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class ConvertJavaMapToJson {

@Test
public void convertMapToJson() {
    SortedMap<String, String> elements = new TreeMap();
    elements.put("Key1", "Value1");
    elements.put("Key2", "Value2");
    elements.put("Key3", "Value3");

    Gson gson = new Gson();
    Type gsonType = new TypeToken<HashMap>(){}.getType();
    String gsonString = gson.toJson(elements,gsonType);
    System.out.println(gsonString);
}
}

For org.json

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
</dependencies>


import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;

public class ConvertJavaMapToJson {

@Test
public void convertMapToJson() {
    Map<String, String> elements = new HashMap<>();
    elements.put("Key1", "Value1");
    elements.put("Key2", "Value2");
    elements.put("Key3", "Value3");

    JSONObject json = new JSONObject(elements);

    System.out.println(json);
}
}

CodePudding user response:

Assuming your map is of type Map<Integer,String>, you can define the following class:

public class IdName {
    private final int id;
    private final String name;

    public IdName(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

You will then want to convert your map into a collection of IdNames:

        List<IdName> list = map.entrySet().stream()
                .map((e)->new IdName(e.getKey(),e.getValue()))
                .collect(Collectors.toList());

and then convert that collection to JSON. Example with Jackson:

String json = mapper.writeValueAsString(list);
  • Related