Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 780
João Felipe Leonello Avatar asked Jul 08 '26 08:07

João Felipe Leonello


2 Answers

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);
}
}
like image 148
Jitendra Nandre Avatar answered Jul 09 '26 22:07

Jitendra Nandre


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);
like image 28
Maurice Perry Avatar answered Jul 09 '26 22:07

Maurice Perry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!