Home > Java > javaTutorial > body text

How to use JsonConfig in Java to convert bean to JSON object and exclude certain properties?

王林
Release: 2023-09-01 18:37:07
forward
1505 people have browsed it

How to use JsonConfig in Java to convert bean to JSON object and exclude certain properties?

#The JsonConfig class is a utility class that helps configure the serialization process. We can use the setExcludes() method of the JsonConfig class to convert a bean into a JSON object and exclude some of its properties, and pass this JSON configuration instance to the parameter of the static method fromObject() of JSONObject.

Syntax

public void setExcludes(String[] excludes)
Copy after login

In the below example, we can convert bean to a JSON object by excluding some of the properties.

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;
      }
   }
}
Copy after login

In the below The age and address attributes can be excluded from the output.

Output

{
   "firstName": "Raja",
   "lastName": "Ramesh"
}
Copy after login

The above is the detailed content of How to use JsonConfig in Java to convert bean to JSON object and exclude certain properties?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template