JavaでJsonConfigを使用して一部のプロパティを除外することにより、BeanをJSONオブジェクトに変換するにはどうすればよいですか?
public void setExcludes(String[] excludes)
以下の例では、一部のプロパティを除外することで、BeanをJSONオブジェクトに変換できます。
例
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BeanToJsonExcludeTest {
public static void main(String[] args) {
Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"age", "address"});
JSONObject obj = JSONObject.fromObject(student, jsonConfig);
System.out.println(obj.toString(3)); //pretty print JSON
}
public static class Student {
private String firstName, lastName, address;
private int age;
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;
}
}
} 以下の出力では、年齢 およびアドレス プロパティを除外できます。
{
"firstName": "Raja",
"lastName": "Ramesh"
} -
JavaでJSON文字列をJSONオブジェクトに変換するにはどうすればよいですか?
JSON JavaScript Object Notationの略です 転送に使用できます およびストレージ データの。 JSONObject 文字列からテキストを解析して、マップのようなオブジェクトを生成できます 。オブジェクトは、そのコンテンツを操作し、JSON準拠のオブジェクトシリアル化を生成するためのメソッドを提供します。 JSONArray 文字列からテキストを解析して、ベクトルのようなオブジェクトを生成できます 。オブジェクトは、そのコンテンツを操作し、JSON準拠の配列シリアル化を生成するためのメソッドを提供します。 以下の2つの例では、JSON文字列をJSONオブ
-
JavaオブジェクトをJSONに変換する方法
このチュートリアルでは、JacksonとGsonの2つのライブラリを使用してJavaオブジェクトをJSONに変換する方法を示します。 標準のPOJOであるPersonクラスを使用します。人物オブジェクトを作成したら、別のライブラリを使用してそれをJSONに変換できます。 Person.java import java.util.List; import java.util.Map; public class Person { String name; Integer age; List<String> hobbies; Map<Str