ホームページ  >  記事  >  Java  >  Java で JsonConfig を使用して Bean を JSON オブジェクトに変換し、特定のプロパティを除外するにはどうすればよいですか?

Java で JsonConfig を使用して Bean を JSON オブジェクトに変換し、特定のプロパティを除外するにはどうすればよいですか?

王林
王林転載
2023-09-01 18:37:071436ブラウズ

Java で JsonConfig を使用して Bean を JSON オブジェクトに変換し、特定のプロパティを除外するにはどうすればよいですか?

#JsonConfig クラスは、シリアル化プロセスの構成に役立つユーティリティ クラスです。 JsonConfig クラスの setExcludes() メソッドを使用して、Bean を JSON オブジェクトに変換し、そのプロパティの一部を除外し、この JSON 構成インスタンスを JSONObject の静的メソッド fromObject() のパラメーターに渡すことができます。

構文

public void setExcludes(String[] excludes)

以下の例では、一部のプロパティを除外することで、Bean を JSON オブジェクトに変換できます。

Example

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;
      }
   }
}

以下の age 属性と address 属性は出力から除外できます。

出力

{
   "firstName": "Raja",
   "lastName": "Ramesh"
}

以上がJava で JsonConfig を使用して Bean を JSON オブジェクトに変換し、特定のプロパティを除外するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。