Java nodrošina divas ļoti spēcīgas bibliotēkas darbam ar JSON datiem, t.i., DŽEKSONS un Gsons bibliotēkas. Mums bieži ir jāpārveido JSON atbildes kartē, lai viegli strādātu ar atgrieztajiem JSON datiem.
Mēs varam viegli pārvērst JSON datus kartē, jo JSON formāts būtībā ir atslēgu un vērtību pāru grupēšana, un kartē dati tiek glabāti arī atslēgu un vērtību pāros.
Sridevi
Sapratīsim, kā mēs varam izmantot gan JACKSON, gan Gson bibliotēkas, lai pārveidotu JSON datus kartē. Mēs arī saprotam, kā mēs varam izmantot abas bibliotēkas, lai pārveidotu kartes datus par JSON.
Pieņemsim, ka sistēmā ir fails Sample.json, kurā ir šādi dati:
{ 'Name' : 'Donal', 'Mobile' : '89346724', 'Designation' : 'Sr. Salesforce Developer', 'Pet' : 'Dog', 'Address' : 'AMERICA' }
Džeksona bibliotēka
Lai JSON datus pārveidotu par Java Map, mēs izmantojam JACKSON bibliotēku. Mēs pievienojam šādu atkarību POM.xml failam, lai strādātu ar JACKSON bibliotēku.
com.fasterxml.jackson.core jackson-databind 2.5.3
Īstenosim loģiku JSON datu konvertēšanai kartē, izmantojot klases ObjectMapper, File un TypeReference.
JacksonConvertJSONToMap.java
hasnext java
// import required classes and packages package javaTpoint.JavaExample; import java.io.File; // for reading file data import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; // create JacksonConvertJSONToMap class to convert JSON data into Java Map public class JacksonConvertJSONToMap { // main() method start public static void main(String args[]) { // create instance of the ObjectMapper class to map JSON data ObjectMapper mapper = new ObjectMapper(); // create instance of the File class File fileObj = new File('C:\Users\rastogi ji\OneDrive\Desktop\Sample.json'); // use try-catch block to convert JSON data into Map try { // read JSON data from file using fileObj and map it using ObjectMapper and TypeReference classes Map userData = mapper.readValue( fileObj, new TypeReference<map>() { }); // print all key-value pairs System.out.println('Name : ' + userData.get('Name')); System.out.println('Mobile : ' + userData.get('Mobile')); System.out.println('Designation : ' + userData.get('Designation')); System.out.println('Pet : ' + userData.get('Pet')); System.out.println('Address : ' + userData.get('Address')); } catch (Exception e) { // show error message e.printStackTrace(); } } } </map>
Izvade:
Apskatīsim vēl vienu Džeksona bibliotēkas piemēru, lai saprastu, kā Java karti var pārveidot par JSON, jo mums bieži ir jānosūta kartes dati API kā JSON. Tātad šajā piemērā mēs konvertējam kartes datus par JSON un saglabājam tos failā.
c++ pāris
JacksonConvertMapToJson.java
// import required classes and packages package javaTpoint.JavaExample; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.fasterxml.jackson.databind.ObjectMapper; //create JacksonConvertMapToJSON class to convert Map data into JSON public class JacksonConvertMapToJSON { // main() method start public static void main(String args[]) { // create instance of the ObjectMapper class ObjectMapper mapper = new ObjectMapper(); // declare and initialize map (key is of type String and value is of type Object) Map userData = new HashMap(); // declare variables and array to store user entered data String name, price, model; String colors[]; // create an instance of the Scanner class Scanner sc = new Scanner(System.in); // take inputs from the user and store them to the variables System.out.println('Enter the name of the car: '); name = sc.nextLine(); System.out.println('Enter the modal number of the car: '); model = sc.nextLine(); System.out.println('Enter the price of the car: '); price = sc.nextLine(); colors = new String[3]; colors[0] = 'Red'; colors[1] = 'Black'; colors[2] = 'White'; // close Scanner class object sc.close(); // fill userData map userData.put('Car', name); userData.put('Price', price); userData.put('Model', model); userData.put('Colors', colors); // use try-catch block to convert Java map into JSON try { // use ObjectMapper class to convert Map data into JSON and write it into Sample.json file mapper.writeValue(new File('C:\Users\rastogi ji\OneDrive\Desktop\Sample.json'), userData); System.out.println('Map data successfully written to the Sample.json file.'); } catch (Exception e) { // handle exception e.printStackTrace(); } } }
Izvade:
Gsona bibliotēka
Gsons bibliotēka ir vēl viena bibliotēka, kuru mēs varam izmantot, lai pārveidotu JSON datus kartē vai kartes datus JSON. Lai izmantotu Gson bibliotēku, failā POM.xml ir jāpievieno šāda atkarība.
com.google.code.gson gson 2.8.3
GsonConvertJSONToMap.java
skeneris.next java
//import required classes and packages package javaTpoint.JavaExample; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; //create GsonConvertJSONToMap class to convert JSON data into Java Map public class GsonConvertJSONToMap { // main() method start public static void main(String args[]) { // create variable loc that store location of the Sample.json file String loc = 'C:\Users\rastogi ji\OneDrive\Desktop\Sample.json'; String result; try { // read byte data from the Sample.json file and convert it into String result = new String(Files.readAllBytes(Paths.get(loc))); // store string data into Map by using TypeToken class Map userData = new Gson().fromJson(result, new TypeToken<hashmap>() { }.getType()); // print all key-value pairs System.out.println('Name : ' + userData.get('Name')); System.out.println('Mobile : ' + userData.get('Mobile')); System.out.println('Designation : ' + userData.get('Designation')); System.out.println('Pet : ' + userData.get('Pet')); System.out.println('Address : ' + userData.get('Address')); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } </hashmap>
Izvade:
Apskatīsim vēl vienu Gson bibliotēkas piemēru, lai saprastu, kā pārvērst Java karti par JSON. Gson bibliotēkas izmantošana nedaudz atšķiras no Džeksona bibliotēkas.
GsonConvertMapToJson.java
//import required classes and packages package javaTpoint.JavaExample; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.google.gson.Gson; //create GsonConvertMapToJson class to convert Map data into JSON public class GsonConvertMapToJson { // main() method start public static void main(String args[]) { // declare and initialize map(key is of type String and value is of type Object) Map userData = new HashMap(); // declare variables and array to store user entered data String name, price, model; String colors[]; // create an instance of the Scanner class Scanner sc = new Scanner(System.in); // take inputs from the user and store them to the variables System.out.println('Enter the name of the car: '); name = sc.nextLine(); System.out.println('Enter the modal number of the car: '); model = sc.nextLine(); System.out.println('Enter the price of the car: '); price = sc.nextLine(); colors = new String[3]; colors[0] = 'Red'; colors[1] = 'Black'; colors[2] = 'White'; // close Scanner class object sc.close(); // fill userData map userData.put('Car', name); userData.put('Price', price); userData.put('Model', model); userData.put('Colors', colors); // use try-catch block to convert Java map into JSON try (FileWriter file = new FileWriter('C:\Users\rastogi ji\OneDrive\Desktop\Sample.json')) { // create instance of the Gson Gson gsonObj = new Gson(); // convert userData map to json string String jsonStr = gsonObj.toJson(userData); // use write() of File to write json string into file file.write(jsonStr); // use flush() method to flushes stream file.flush(); System.out.println('Map data successfully written to the Sample.json file.'); } catch (IOException e) { // error handling and exceptions e.printStackTrace(); } } }
Izvade: