/java/

Convert Json File to Map (jackson)

2015-06-27 14:27:57

Test

package btbw.pl;

import java.io.File;
import java.util.Map;

public class App {

    public static void main(String[] args) {

        Map

<string, object=""> map1 = JsonUtil.getMap("{\"NAME\":\"Michał\", \"SURNAME\":\"Szałkowski\"}");
        System.out.println(map1);

        Map<string, object=""> map2 = JsonUtil.getMap(new File("test.json"));
        System.out.println(map2);

        JsonUtil.toFile(map2, new File("test2.json"));

    }

}

JsonUtil

package btbw.pl;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JsonUtil {

    public static Map<string, object=""> getMap(String string) {

        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.readValue(string, new TypeReference<hashmap<string, object="">&gt;() {});
        } catch (IOException e) {
            System.out.println("Error:" + e.getMessage());
            return new HashMap<string, object="">();
        }

    }

    public static Map<string, object=""> getMap(File file) {

        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.readValue(file, new TypeReference<hashmap<string, object="">&gt;() {});
        } catch (IOException e) {
            System.out.println("Error:" + e.getMessage());
            return new HashMap<string, object="">();
        }

    }

    public static void toFile(Map<string, object=""> map, File file) {

        ObjectMapper mapper = new ObjectMapper();

        try {
            mapper.writeValue(file, map);
        } catch (Exception e) {
            System.out.println("Error:" + e.getMessage());
        }
    }
}

pom.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<project http:="" maven-4.0.0.xsd&quot;="" maven.apache.org="" xmlns='"http://maven.apache.org/POM/4.0.0"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://maven.apache.org/POM/4.0.0'>
<modelversion>4.0.0</modelversion>
<groupid>btbw.pl</groupid>
<artifactid>JSONObject</artifactid>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupid>org.codehaus.jackson</groupid>
<artifactid>jackson-core-asl</artifactid>
<version>1.9.2</version>
</dependency>
<dependency>
<groupid>org.codehaus.jackson</groupid>
<artifactid>jackson-mapper-asl</artifactid>
<version>1.9.2</version>
</dependency>
</dependencies>
</project>