Convert Map to JSON in Java

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

Upvotes: 3

Views: 9710

Answers (2)

Maurice Perry
Maurice Perry

Reputation: 9651

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);

Upvotes: 1

Jitendra Nandre
Jitendra Nandre

Reputation: 161

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);
}
}

Upvotes: 2

Related Questions