How To Convert Map To Json To Hashmap Inward Java? Illustration Tutorial
In the terminal duad of years, JSON piece of cake took over XML equally preferred format to transfer information from customer to server together with vice-versa. Because of increasing usage of JSON, Java developers are also getting a goodness exposure of JSON. If you lot are writing spider web services e.g. traditional GET based services, or modern RESTful spider web service, you lot also receive got to supply back upwards for JSON format along alongside TEXT together with XML. Though criterion Java API doesn't back upwards encoding together with decoding of JSON from Java Object, at that spot are a bunch of goodness open rootage JSON libraries available to Java developers. Jackson together with GSON are 2 of the most pop such library to bargain alongside JSON information inwards Java. They non exclusively permit you lot to parse JSON String to Java Object but also to practice JSON formatted String from Java object. They also supply utilities to bargain alongside formatting together with other day-to-day features you lot demand to bargain alongside JSON formatted data.
One of such characteristic is to straight convert a JSON reply to java.util.Map object. Since JSON is also a commutation value pair, it seems piece of cake to convert it into a Map, a Java information construction for belongings commutation value pair, but if you lot receive got to practice it manually together with so it's a hurting because you lot receive got to top away alongside every JSON element, extract it together with and so lay it into a HashMap. Thankfully, you lot don't demand to practice that because Jackson provides features to convert JSON String to Map inwards Java.
In this Java JSON tutorial, nosotros are going to showtime larn how to convert a Java HashMap to a JSON String past times using the Jackson's JSON Parsing API. In the minute part, we'll convert the JSON String to Java HashMap objects, which is similar to receiving a JSON reply from spider web service together with and so creating an HashMap of domain objects from them. Converting Map to/from JSON comes naturally because they receive got a pretty similar representation together with usage.
When you lot compare this to XML, it's really concise because at that spot is no opening together with closing tags thus for a large amount of data, JSON is much smaller than XML.
Now, suppose you lot are writing spider web services to mail details of products to customer e.g. programming books. Let's tell customer mail a majority to plow over all Java programming books, right away you lot tin render all books inwards whatever format customer requests e.g. Text, XML, or JSON. For XML, you lot tin utilisation JAXB together with some other XML marshaling together with unmarshalling utility comes inwards Java but how practice you lot convert a listing of those Java object to JSON formatted String?
The respond is past times using opened upwards rootage JSON parsing libraries similar Jackson or Gson. Jackson is i of the most characteristic rich, fast, together with zero-dependency library i.e. does non rely on other packages beyond JDK. It provides JSON parser/JSON generator equally foundation edifice block together with adds a powerful Data binder together with Tree Model equally optional improver blocks. It also supports streaming which is essential for reading large JSON files together with converting them into collection of Java object
By using Jackson API, you lot tin read together with write JSON String either equally a current of tokens (Streaming API), equally Plain Old Java Objects (POJOs, information bind) or equally Trees (Tree Model) inwards your Java application. It also provides pretty impress functionality to nicely format JSON String for increased readability together with troubleshooting.
One of the large problems is to position which Jackson JAR file to download or add together equally a dependency inwards your pom.xml file. There are lots together with lots of Jackson API jars, which volition appear if you lot search for "Jackson" inwards Eclipse Maven repository search.
Maven Dependency for Jackson Libary
You demand to include the next dependency inwards your project's pom.xml file if you lot are using Maven to construct your project:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.12</version>
</dependency>
Alternatively, you lot tin indluce next JAR files inwards your project's Classpath to compile together with run this JSON example:
C:\.m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar
The Jackson JAR files are taken from Maven dependencies itself. If you lot are using Eclipse together with so you lot tin encounter that which JAR file has been downloaded past times Maven for your projection past times expanding Maven dependency tab inwards Eclipse. Btw, if you lot are interested inwards learning to a greater extent than nearly JSON format itself, together with so should read Beginning JSON past times Ben Smit, i of the best books to larn JSON format.
Here nosotros receive got three JSON fields together with i JSON array, which is for friends. Now, past times using ObjectMapper's readValue() method we'll convert this JSON input to HashMap inwards Java. You simply demand to supply the JSON file together with an HashMap together with Jackson volition receive got attention of rest. If you lot desire to larn to a greater extent than nearly JSON parsing inwards Java, you lot tin also read How to Program Java past times Dietel together with Dietel.
Java Program to convert HashMap to JSON together with Vice-Versa
When you lot run this code, it volition practice a map.json file inwards your projection directory, the directory from where you lot receive got run the Java ascendancy alongside next JSON String.
One of such characteristic is to straight convert a JSON reply to java.util.Map object. Since JSON is also a commutation value pair, it seems piece of cake to convert it into a Map, a Java information construction for belongings commutation value pair, but if you lot receive got to practice it manually together with so it's a hurting because you lot receive got to top away alongside every JSON element, extract it together with and so lay it into a HashMap. Thankfully, you lot don't demand to practice that because Jackson provides features to convert JSON String to Map inwards Java.
In this Java JSON tutorial, nosotros are going to showtime larn how to convert a Java HashMap to a JSON String past times using the Jackson's JSON Parsing API. In the minute part, we'll convert the JSON String to Java HashMap objects, which is similar to receiving a JSON reply from spider web service together with and so creating an HashMap of domain objects from them. Converting Map to/from JSON comes naturally because they receive got a pretty similar representation together with usage.
What is JSON together with Jackson library?
For those, who are non familiar alongside JSON, it's means to stand upwards for your information similar to XML where you lot tin define custom tags to specify your data. In the instance of JSON, it's simply a key-value pairs but it also provides JSON arrays to stand upwards for listing values equally shown below:When you lot compare this to XML, it's really concise because at that spot is no opening together with closing tags thus for a large amount of data, JSON is much smaller than XML.
Now, suppose you lot are writing spider web services to mail details of products to customer e.g. programming books. Let's tell customer mail a majority to plow over all Java programming books, right away you lot tin render all books inwards whatever format customer requests e.g. Text, XML, or JSON. For XML, you lot tin utilisation JAXB together with some other XML marshaling together with unmarshalling utility comes inwards Java but how practice you lot convert a listing of those Java object to JSON formatted String?
The respond is past times using opened upwards rootage JSON parsing libraries similar Jackson or Gson. Jackson is i of the most characteristic rich, fast, together with zero-dependency library i.e. does non rely on other packages beyond JDK. It provides JSON parser/JSON generator equally foundation edifice block together with adds a powerful Data binder together with Tree Model equally optional improver blocks. It also supports streaming which is essential for reading large JSON files together with converting them into collection of Java object
By using Jackson API, you lot tin read together with write JSON String either equally a current of tokens (Streaming API), equally Plain Old Java Objects (POJOs, information bind) or equally Trees (Tree Model) inwards your Java application. It also provides pretty impress functionality to nicely format JSON String for increased readability together with troubleshooting.
One of the large problems is to position which Jackson JAR file to download or add together equally a dependency inwards your pom.xml file. There are lots together with lots of Jackson API jars, which volition appear if you lot search for "Jackson" inwards Eclipse Maven repository search.
Maven Dependency for Jackson Libary
You demand to include the next dependency inwards your project's pom.xml file if you lot are using Maven to construct your project:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.12</version>
</dependency>
Alternatively, you lot tin indluce next JAR files inwards your project's Classpath to compile together with run this JSON example:
C:\.m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar
The Jackson JAR files are taken from Maven dependencies itself. If you lot are using Eclipse together with so you lot tin encounter that which JAR file has been downloaded past times Maven for your projection past times expanding Maven dependency tab inwards Eclipse. Btw, if you lot are interested inwards learning to a greater extent than nearly JSON format itself, together with so should read Beginning JSON past times Ben Smit, i of the best books to larn JSON format.
How to convert HashMap to JSON String inwards Java
Here is a consummate illustration of converting a Java Map to JSON String inwards Java. In fellowship to demonstrate the example, I receive got showtime created a JSON String past times converting a HashMap to JSON using Jackson API's ObjectMapper.writeValue() method. The output JSON String looks similar following:{ "friends":["Rick","Ron","Victor"], "name":"John", "mobile":847339282, "city":"London" } Here nosotros receive got three JSON fields together with i JSON array, which is for friends. Now, past times using ObjectMapper's readValue() method we'll convert this JSON input to HashMap inwards Java. You simply demand to supply the JSON file together with an HashMap together with Jackson volition receive got attention of rest. If you lot desire to larn to a greater extent than nearly JSON parsing inwards Java, you lot tin also read How to Program Java past times Dietel together with Dietel.
Java Program to convert HashMap to JSON together with Vice-Versa
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; /** * Java Program to convert Map to JSON String * * @author Javin Paul */ public class Testing { public static void main(String args[]) { ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> mapObject = new HashMap<String, Object>(); mapObject.put("name", "John"); mapObject.put("city", "London"); mapObject.put("mobile", 847339282); List<Object> friends = new ArrayList<Object>(); friends.add("Rick"); friends.add("Ron"); friends.add("Victor"); mapObject.put("friends", friends); try { objectMapper.writeValue(new File("map.json"), mapObject); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
When you lot run this code, it volition practice a map.json file inwards your projection directory, the directory from where you lot receive got run the Java ascendancy alongside next JSON String.
{ "friends":["Rick","Ron","Victor"], "name":"John", "mobile":847339282, "city":"London" } How to convert JSON String to HashMap inwards Java
This is the reverse of what nosotros receive got done inwards the previous section, inwards this percentage I'll convert the JSON String to HashMap inwards Java using Jackson. This is a to a greater extent than mutual scenario if you lot are consuming Web Services inwards JSON format together with created a map of users, books, orders, or whatever other domain objects. In this example, we'll utilisation the JSON string created inwards the previous example.
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; /** * Java Program to convert JSON String to Map * * @author Javin Paul */ public class Testing { public static void main(String args[]) { ObjectMapper mapper = new ObjectMapper(); try { File jsonFile = new File("map.json"); Map<String, Object> mapObject = mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() { }); System.out.println("name : " + mapObject.get("name")); System.out.println("city : " + mapObject.get("city")); System.out.println("mobile : " + mapObject.get("mobile")); System.out.print("friends : "); List<String> listing = (List<String>) mapObject.get("friends"); for (String elevate : list) { System.out.print(name + " "); } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Output: elevate : John metropolis : London mobile : 847339282 friends : Rick Ron Victor
That's all about how to convert Map to JSON inwards Java together with opposite, JSON String to HashMap. Once you lot know the correct JSON library to use, your task volition top away much easier. No doubt, Jackson is i of the best JSON parsing library available to Java developers together with you lot must pass some fourth dimension to larn this API, it volition pay inwards long run. If you lot were to larn simply i JSON library, I advise larn Jackson, because i time you lot larn how to utilisation Jackson properly, you lot tin grip most of the existent globe requirements related to producing together with parsing JSON data. If you lot looking for a goodness majority to larn nearly how to bargain alongside JSON information inwards Java application, I advise reading Java XML together with JSON past times Jeff Frierson, he explains a lot nearly parsing together with creating JSON formatted output from Java objects.
Further Learning
Master Java Web Services together with REST API alongside Spring Boot
REST API Design, Development & Management
tutorial)
P.S. - If you lot are looking for online grooming to larn how to develop RESTful Web Services inwards Java using Spring framework, I advise you lot joining Eugen Paraschiv's REST alongside Spring course. The course of written report has diverse options depending upon your sense marking together with how much you lot desire to larn e.g. beginner's class, intermediate class, together with original class. You tin bring together the i which suits you lot better, though I advise joining the master class if you lot are serious nearly becoming an goodness Java REST developer.



Komentar
Posting Komentar