import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParsingExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObj = new JSONObject(jsonString);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
String jsonArrayString = "[\"apple\", \"banana\", \"orange\"]";
JSONArray jsonArray = new JSONArray(jsonArrayString);
System.out.println("Fruits:");
for (int i = 0; i < jsonArray.length(); i++) {
String fruit = jsonArray.getString(i);
System.out.println(fruit);
}
}
}
Name: John
Age: 30
City: New York
Fruits:
apple
banana
orange
import com.google.gson.Gson;
public class JsonParsingExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("City: " + person.getCity());
}
class Person {
String name;
int age;
String city;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCity() {
return city;
}
}
}
Name: John
Age: 30
City: New York