Flexjson हल्की लाइब्रेरी है जिसका उपयोग Java ऑब्जेक्ट्स को JSON फॉर्मेट में सीरियलाइज़ और डिसीरियलाइज़ करने के लिए किया जाता है। हम JSONSerializer क्लास के serialize() मेथड का उपयोग करके मैप को भी सीरियलाइज़ कर सकते हैं, यह टारगेट इंस्टेंस की शैलो सीरियलाइज़ेशन करता है।
सिंटैक्स
public String serialize(Object target)
उदाहरण
import flexjson.JSONSerializer;
import java.util.*;
public class JsonSerializeMapTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
Student student = new Student("Adithya", "Sai", 28, "Hyderabad");
Map<String, Object> map = new HashMap<String, Object>();
map.put("Student1", "Raja");
map.put("Student2", "Ravi");
map.put("my_student", student);
String jsonStr = serializer.serialize(map);
System.out.println(jsonStr);
}
}
// Student क्लास
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
public Student() {}
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public int getAge() { return age; }
public String getAddress() { return address; }
public String toString() {
return "Student[ " + "firstName = " + firstName + ", lastName = " + lastName + ", age = " + age + ", address = " + address + " ]";
}
}
आउटपुट
{
"my_student": {
"address": "Hyderabad",
"age": 28,
"class": "Student",
"firstName": "Adithya",
"lastName": "Sai"
},
"Student1": "Raja",
"Student2": "Ravi"
}