How To Convert Map To Json To Hashmap Inwards Java? Event Tutorial

In the final distich of years, JSON slow took over XML equally preferred format to transfer information from customer to server in addition to 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 furnish back upwards for JSON format along amongst TEXT in addition to XML. Though touchstone Java API doesn't back upwards encoding in addition to decoding of JSON from Java Object, at that topographic point are a bunch of goodness open beginning JSON libraries available to Java developers. Jackson in addition to GSON are 2 of the most pop such library to bargain amongst JSON information inwards Java.   They non exclusively let you lot to parse JSON String to Java Object but also to do JSON formatted String from Java object. They also furnish utilities to bargain amongst formatting in addition to other day-to-day features you lot ask to bargain amongst JSON formatted data.

One of such characteristic is to straight convert a JSON response to java.util.Map object. Since JSON is also a telephone commutation value pair, it seems like shooting fish in a barrel to convert it into a Map, a Java information construction for belongings telephone commutation value pair, but if you lot receive got to do it manually so it's a hurting because you lot receive got to leave of absence amongst every JSON element, extract it in addition to so pose it into a HashMap. Thankfully, you lot don't ask to do that because Jackson provides features to convert JSON String to Map inwards Java.

In this Java JSON tutorial, nosotros are going to get-go acquire how to convert a Java HashMap to a JSON String past times using the Jackson's JSON Parsing API. In the 2d part, we'll convert the JSON String to Java HashMap objects, which is similar to receiving a JSON response from spider web service in addition to so creating an HashMap of domain objects from them. Converting Map to/from JSON comes naturally because they receive got a pretty similar representation in addition to usage.




What is JSON in addition to Jackson library?

For those, who are non familiar amongst JSON, it's means to correspond your information similar to XML where you lot tin move 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 correspond listing values equally shown below:

When you lot compare this to XML, it's real concise because at that topographic point is no opening in addition to 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 post details of products to customer e.g. programming books. Let's tell customer post a mass to plough over all Java programming books, right away you lot tin move render all books inwards whatever format customer requests e.g. Text, XML, or JSON. For XML, you lot tin move utilization JAXB in addition to some other XML marshaling in addition to unmarshalling utility comes inwards Java but how do you lot convert a listing of those Java object to JSON formatted String?

The answer is past times using opened upwards beginning JSON parsing libraries similar Jackson or Gson. Jackson is ane of the most characteristic rich, fast, in addition to zero-dependency library i.e. does non rely on other packages beyond JDK. It provides JSON parser/JSON generator equally foundation edifice block in addition to adds a powerful Data binder in addition to Tree Model equally optional summation blocks. It also supports streaming which is essential for reading large JSON files in addition to converting them into collection of Java object


By using Jackson API, you lot tin move read in addition to 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 in addition to 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 in addition to 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 ask to include the next dependency inwards your project's pom.xml file if you lot are using Maven to gear upwards your project:

<dependency>
  <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-xc</artifactId>
   <version>1.9.12</version>
</dependency>

Alternatively, you lot tin move indluce next JAR files inwards your project's Classpath to compile in addition to 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 so you lot tin move 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 close JSON format itself, so should read  Beginning JSON past times Ben Smit, ane of the best books to acquire JSON format.

 JSON slow took over XML equally preferred format to transfer information from customer to server in addition to  How to Convert Map to JSON to HashMap inwards Java? Example Tutorial



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 social club to demonstrate the example, I receive got get-go 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 iii JSON fields in addition to ane 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 ask to furnish the JSON file in addition to an HashMap in addition to Jackson volition receive got tending of rest. If you lot desire to acquire to a greater extent than close JSON parsing inwards Java, you lot tin move also read How to Program Java past times Dietel in addition to Dietel.

 JSON slow took over XML equally preferred format to transfer information from customer to server in addition to  How to Convert Map to JSON to HashMap inwards Java? Example Tutorial



Java Program to convert HashMap to JSON in addition to 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 do a map.json file inwards your projection directory, the directory from where you lot receive got run the Java ascendency amongst next JSON String.

{ "friends":["Rick","Ron","Victor"], "name":"John", "mobile":847339282, "city":"London" }

 JSON slow took over XML equally preferred format to transfer information from customer to server in addition to  How to Convert Map to JSON to HashMap inwards Java? Example Tutorial



How to convert JSON String to HashMap inwards Java
This is the contrary of what nosotros receive got done inwards the previous section, inwards this constituent 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 in addition to created a map of users, books, orders, or whatever other domain objects. In this example, we'll utilization 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 cite : list) {   System.out.print(name + " ");   }    } catch (JsonGenerationException e) {   e.printStackTrace();   } catch (JsonMappingException e) {   e.printStackTrace();   } catch (IOException e) {   e.printStackTrace();   }    }  }  Output: cite : John metropolis : London mobile : 847339282 friends : Rick Ron Victor

That's all about how to convert Map to JSON inwards Java in addition to opposite, JSON String to HashMap. Once you lot know the correct JSON library to use, your chore volition leave of absence much easier. No doubt, Jackson is ane of the best JSON parsing library available to Java developers in addition to you lot must pass some fourth dimension to acquire this API, it volition pay inwards long run. If you lot were to acquire simply ane JSON library, I propose acquire Jackson, because ane time you lot acquire how to utilization Jackson properly, you lot tin move grip most of the existent the world requirements related to producing in addition to parsing JSON data. If you lot looking for a goodness mass to acquire close how to bargain amongst JSON information inwards Java application, I propose reading Java XML in addition to JSON past times Jeff Frierson, he explains a lot close parsing in addition to creating JSON formatted output from Java objects.

Further Learning
Master Java Web Services in addition to REST API amongst Spring Boot
REST API Design, Development & Management
tutorial)
  • 3 Ways to parse JSON String inwards Java? (tutorial)
  • How to convert JSON array to String array inwards Java? (example)
  • How to convert a Map to JSON inwards Java? (tutorial)
  • How to utilization Google Protocol Buffer inwards Java? (tutorial)
  • How to utilization Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST in addition to RESTful Web Services (books)

  • P.S. - If you lot are looking for online preparation to acquire how to develop RESTful Web Services inwards Java using Spring framework, I propose you lot joining Eugen Paraschiv's REST amongst Spring course. The course of pedagogy has diverse options depending upon your sense score in addition to how much you lot desire to acquire e.g. beginner's class, intermediate class, in addition to master copy class. You tin move bring together the ane which suits you lot better, though I propose joining the master class if you lot are serious close becoming an practiced Java REST developer.

    0 Response to "How To Convert Map To Json To Hashmap Inwards Java? Event Tutorial"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel