📜  如何在Java中将 Map 转换为 JSON 到 HashMap?

📅  最后修改于: 2021-10-28 02:52:56             🧑  作者: Mango

JSON 是一种开放的标准文件格式,是一种更简单的数据交换格式,有助于人类传输数据。大多数应用程序显示 JSON 数据,因此现在 JSON 已成为传输数据的强制性媒体。在这里我们将了解如何将 Map 转换为 JSON,对于 Map,让我们将 HashMap 作为输入数据集。

安装:

第 1 步:对于与控制台相关的Java部分,我们需要从下面提供的链接下载 jar。下载 jars,解压它们并将 jars 放在项目的构建路径中

步骤 2(A):对于 Maven 项目,“ pom.xml 文件”中需要以下依赖项


  com.fasterxml.jackson.core
   jackson-databind
   2.9.6

Step 2(B):对于Gradle项目,如下:

dependencies
{

   // a dependency on Jackson Databind
   implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.9'
}

执行:

让我们看一个数据的 HashMap 示例。 HashMap 的优势是以非同步方式将数据存储在键值对中。

我们将使用 studentId、studentFirstName、studentLastName、studentStream 和 studentMarks 作为 HashMap 的关键元素。 使用 com.fasterxml.jackson.databind.ObjectMapper,我们将 HashMap 转换为 JSON。让我们看一个简单的Java应用程序。 ObjectMapper 是 Jackson 库中的主要基本类,它有助于从基本 POJO(Plain Old Java Objects)或包含键/值对的 HashMap 读取和写入 JSON。

在这里,我们将在代码中使用名为“writeValueAsString()”的方法,该方法可用于将任何Java值序列化为字符串。这里我们将数据的 HashMap 作为对象传递,并将它们序列化为字符串。使用 ObjectMapper 时,它会写入 JSON 字符串。

示例 1:

Java
// Java Program to Convert Map to JSON to HashMap
 
// Importing required basic libraries
// Importing required classes from com.fasterxml.jackson
// package
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
 
// Main class
// MapToJSONExample
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of HashMap class
        // Declaring object of String and Object type
        HashMap studentHashmap
            = new HashMap();
 
        // Let us hold studentHashmap containing
        // 1. studentId
        // 2. studentFirstName
        // 3. studentLastName
        // 4. studentStream
        // 5. studentMarks
 
        // Custom input entries
        studentHashmap.put("studentId", 1);
        studentHashmap.put("studentFirstName", "AAA");
        studentHashmap.put("studentLastName", "BBB");
        studentHashmap.put("studentStream", "PCMB");
        studentHashmap.put("studentMarks", "480");
 
        // ObjectMapper object is a reusable object.
        // ObjectMapper is the main essential class in
        // Jackson library which helps for reading and
        // writing JSON, either to and from basic POJOs
        // (Plain Old Java Objects) or from HashMap
        // containing key/value pairs.
        ObjectMapper mapper = new ObjectMapper();
 
        // Try block to check fo exceptions
        try {
 
            // Convert studentHashmap to JSON
            // In method writeValueAsString(Object object),
            // we are using this method in the code and that
            // can be used to serialize any Java value as a
            // String. Here we are passing HashMap of data
            // as object and it serializes them as string .
            // As ObjectMapper is used, it writes JSON
            // string
            String studentJson
                = mapper.writeValueAsString(studentHashmap);
 
            // Print JSON output
            System.out.println(studentJson);
        }
 
        // There are possibilities of following exceptions,
        // so catch block to handle the exceptions
        catch (JsonGenerationException e) {
 
            // Printing the exception along with line number
            // using the printStackTrace() method
            e.printStackTrace();
        }
 
        // Catch block 2
        catch (JsonMappingException e) {
            e.printStackTrace();
        }
 
        // Catch block 3
        // Catching generic input output exceptions
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Java
// Java Program to Convert Map to JSON to HashMap
 
// Importing utility and input output classes
// Importing ObjectMapper class
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
 
// Main class
// To convert JSON to Map
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of ObjectMapper class
        // in the main() method
        ObjectMapper mapper = new ObjectMapper();
 
        // Custom string data in JSON
        String studentJsonData
            = "{\"studentId\":\"1\", \"studentFirstName\":\"AAA\",\"studentLastName\":\"BBB\",\"studentStream\":\"PCMB\",\"studentMarks\":\"480\"}";
 
        // Try block to handle the exceptions
        try {
 
            // Convert JSON string to Map
            // This method deserializes JSON content into a
            // non-container type. In our example as a Map
            // class, JSON content is deserialized.
            Map studentMapData
                = mapper.readValue(studentJsonData,
                                   Map.class);
            System.out.println(studentMapData);
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
 
            // Display and print the exceptions along with
            // line number using printStackTrace() method
            e.printStackTrace();
        }
    }
}


Java
// Java Program illustratiing Simple POJO class only
// containing 3 attributes namely color/type/name
 
public class Automobiles {
 
    // Any kind of automobiles can have these attributes and
    // for simplicity let us keep this
    private String color;
    private String type;
    private String name;
 
    // Constructor 1
    // Default constructor of this class
    public Automobiles() {}
 
    // Constructor 2
    // Parameterized constructor of this class
    public Automobiles(final String color,
                       final String type, final String name)
    {
 
        // This keyword refers to current instance itself
        this.color = color;
        this.type = type;
        this.name = name;
    }
 
    // Method 1
    public String getName() { return name; }
 
    // Method 2
    public void setName(String name) { this.name = name; }
 
    // Method 3
    public String getColor() { return color; }
 
    // Method 4
    public void setColor(final String color)
    {
        this.color = color;
    }
 
    // Method 5
    public String getType() { return type; }
 
    // Method 6
    public void setType(final String type)
    {
        this.type = type;
    }
}


Java
// Java Program to Convert Map to JSON to HashMap
 
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
 
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
 
public class
    SerializationDeserializationFeatureUnitTestExample {
    final String EXAMPLE_JSON
        = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
    final String JSON_CAR
        = "{ \"color\" : \"Red\", \"type\" : \"Honda WRV\", \"year\" : \"2018\" }";
    final String JSON_ARRAY
        = "[{ \"color\" : \"Blue\", \"type\" : \"Sedan\",\"name\" : \"Honda City\" }, { \"color\" : \"Red\", \"type\" : \"Hatchback\",\"name\" : \"Santro\"  }]";
 
    @Test
    public void
    whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly()
        throws Exception
    {
        // ObjectMapper is the main essential class in
        // Jackson library which helps for reading and
        // writing JSON, and in this example it is from POJO
        // class that is our Automobiles class
        final ObjectMapper objectMapper
            = new ObjectMapper();
        // Reason for setting
        // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        // to false is that it will tell Jackson to ignore
        // unknown attributes in all deserializations where
        // that object mapper is used.
        objectMapper.configure(
            DeserializationFeature
                .FAIL_ON_UNKNOWN_PROPERTIES,
            false);
        // readValue(JsonParser p, Class valueType) -
        // This method deserializes JSON content into a
        // non-container type. In our example it is
        // Automobiles class, JSON content is deserialized.
        final Automobiles automobiles
            = objectMapper.readValue(JSON_CAR,
                                     Automobiles.class);
        assertNotNull(automobiles);
    }
 
    @Test
    public void
    whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray()
        throws Exception
    {
        final ObjectMapper objectMapper
            = new ObjectMapper();
        // Reason for setting
        // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        // to true is that it will tell Jackson to consider
        // attributes in all deserializations where that
        // object mapper is used.
        objectMapper.configure(
            DeserializationFeature
                .USE_JAVA_ARRAY_FOR_JSON_ARRAY,
            true);
        final Automobiles[] automobiles
            = objectMapper.readValue(JSON_ARRAY,
                                     Automobiles[].class);
        for (final Automobiles car : automobiles) {
            assertNotNull(car);
        }
        assertTrue(
            automobiles[1].getName().equalsIgnoreCase(
                "Santro"));
        assertTrue(
            automobiles[0].getType().equalsIgnoreCase(
                "Sedan"));
    }
}


输出:

继续下一个示例。在这个例子中,让我们看看如何使用 ObjectMapper 将 JSON 数据转换为 Map。我们将在这里使用 readValue() 将 JSON 内容反序列化为非容器类型。在此示例中,作为 Map 类,JSON 内容被反序列化。

readValue(JsonParser p, Class valueType)

示例 2:

Java

// Java Program to Convert Map to JSON to HashMap
 
// Importing utility and input output classes
// Importing ObjectMapper class
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
 
// Main class
// To convert JSON to Map
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of ObjectMapper class
        // in the main() method
        ObjectMapper mapper = new ObjectMapper();
 
        // Custom string data in JSON
        String studentJsonData
            = "{\"studentId\":\"1\", \"studentFirstName\":\"AAA\",\"studentLastName\":\"BBB\",\"studentStream\":\"PCMB\",\"studentMarks\":\"480\"}";
 
        // Try block to handle the exceptions
        try {
 
            // Convert JSON string to Map
            // This method deserializes JSON content into a
            // non-container type. In our example as a Map
            // class, JSON content is deserialized.
            Map studentMapData
                = mapper.readValue(studentJsonData,
                                   Map.class);
            System.out.println(studentMapData);
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
 
            // Display and print the exceptions along with
            // line number using printStackTrace() method
            e.printStackTrace();
        }
    }
}

输出:

输出说明:

正如我们在示例 1 和示例 2 中看到的那样,在“无法构造实例”/“没有合适的构造函数”/“根名称与预期不匹配”/“找不到类的序列化程序”时,可能会发生JsonMappingException ”等,所以每当有从HashMap到JSON或JSON到HashMap的转换时,都有可能出现上述异常,因此我们需要处理它。除了 JsonGenerationException 和 IOException 也是可能的,我们需要处理它

继续下一个示例,让我们考虑一个复杂的示例并通过 JunitTestCase 提供结果。这里我们将 JSON 内容反序列化为 POJO 类

示例 3(A): POJO 类,即汽车。 Java包含3个属性,即颜色/类型/名称

Java

// Java Program illustratiing Simple POJO class only
// containing 3 attributes namely color/type/name
 
public class Automobiles {
 
    // Any kind of automobiles can have these attributes and
    // for simplicity let us keep this
    private String color;
    private String type;
    private String name;
 
    // Constructor 1
    // Default constructor of this class
    public Automobiles() {}
 
    // Constructor 2
    // Parameterized constructor of this class
    public Automobiles(final String color,
                       final String type, final String name)
    {
 
        // This keyword refers to current instance itself
        this.color = color;
        this.type = type;
        this.name = name;
    }
 
    // Method 1
    public String getName() { return name; }
 
    // Method 2
    public void setName(String name) { this.name = name; }
 
    // Method 3
    public String getColor() { return color; }
 
    // Method 4
    public void setColor(final String color)
    {
        this.color = color;
    }
 
    // Method 5
    public String getType() { return type; }
 
    // Method 6
    public void setType(final String type)
    {
        this.type = type;
    }
}

现在让我们编写 JunitTestCases 并检查 DeserializationFeature 在下面的示例中是如何工作的,如下所示:

示例 3(B):

Java

// Java Program to Convert Map to JSON to HashMap
 
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
 
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
 
public class
    SerializationDeserializationFeatureUnitTestExample {
    final String EXAMPLE_JSON
        = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
    final String JSON_CAR
        = "{ \"color\" : \"Red\", \"type\" : \"Honda WRV\", \"year\" : \"2018\" }";
    final String JSON_ARRAY
        = "[{ \"color\" : \"Blue\", \"type\" : \"Sedan\",\"name\" : \"Honda City\" }, { \"color\" : \"Red\", \"type\" : \"Hatchback\",\"name\" : \"Santro\"  }]";
 
    @Test
    public void
    whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly()
        throws Exception
    {
        // ObjectMapper is the main essential class in
        // Jackson library which helps for reading and
        // writing JSON, and in this example it is from POJO
        // class that is our Automobiles class
        final ObjectMapper objectMapper
            = new ObjectMapper();
        // Reason for setting
        // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        // to false is that it will tell Jackson to ignore
        // unknown attributes in all deserializations where
        // that object mapper is used.
        objectMapper.configure(
            DeserializationFeature
                .FAIL_ON_UNKNOWN_PROPERTIES,
            false);
        // readValue(JsonParser p, Class valueType) -
        // This method deserializes JSON content into a
        // non-container type. In our example it is
        // Automobiles class, JSON content is deserialized.
        final Automobiles automobiles
            = objectMapper.readValue(JSON_CAR,
                                     Automobiles.class);
        assertNotNull(automobiles);
    }
 
    @Test
    public void
    whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray()
        throws Exception
    {
        final ObjectMapper objectMapper
            = new ObjectMapper();
        // Reason for setting
        // DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        // to true is that it will tell Jackson to consider
        // attributes in all deserializations where that
        // object mapper is used.
        objectMapper.configure(
            DeserializationFeature
                .USE_JAVA_ARRAY_FOR_JSON_ARRAY,
            true);
        final Automobiles[] automobiles
            = objectMapper.readValue(JSON_ARRAY,
                                     Automobiles[].class);
        for (final Automobiles car : automobiles) {
            assertNotNull(car);
        }
        assertTrue(
            automobiles[1].getName().equalsIgnoreCase(
                "Santro"));
        assertTrue(
            automobiles[0].getType().equalsIgnoreCase(
                "Sedan"));
    }
}

输出:运行这些 JUnit 之后