groovy
dependencies {
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
}
public class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
import org.json.simple.JSONObject;
public class Main {
public static void main(String[] args) {
User user = new User(1, "John", 30);
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", user.getId());
jsonObject.put("name", user.getName());
jsonObject.put("age", user.getAge());
String jsonStr = jsonObject.toJSONString();
System.out.println(jsonStr);
}
}
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"id\":1,\"name\":\"John\",\"age\":30}";
try {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonStr);
int id = ((Long) jsonObject.get("id")).intValue();
String name = (String) jsonObject.get("name");
int age = ((Long) jsonObject.get("age")).intValue();
User user = new User(id, name, age);
System.out.println(user.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
}