Method 1: Manual Parsing
import org.json.JSONObject;
public class ManualParsingExample {
public static void main(String[] args) {
// Sample JSON data
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Manual parsing using JSONObject
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
// Create Java object
Person person = new Person(name, age, city);
// Output
System.out.println(person);
}
}
Output:
Person{name='John', age=30, city='New York'}
Method 2: Jackson Library
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) throws IOException {
// Sample JSON data
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Using Jackson for JSON to Object conversion
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(json, Person.class);
// Output
System.out.println(person);
}
}
Output:
Person{name='John', age=30, city='New York'}
Method 3: Gson Library
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
// Sample JSON data
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Using Gson for JSON to Object conversion
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
// Output
System.out.println(person);
}
}
Output:
Person{name='John', age=30, city='New York'}
Method 4: JSON-B (Java API for JSON Binding)
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class JsonbExample {
public static void main(String[] args) {
// Sample JSON data
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
// Using JSON-B for JSON to Object conversion
Jsonb jsonb = JsonbBuilder.create();
Person person = jsonb.fromJson(json, Person.class);
// Output
System.out.println(person);
}
}
Output:
Person{name='John', age=30, city='New York'}
Comments (0)