Java reflection implements javabean to json example code
ObjectToJson.java
package com.ObjectToJson; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; public class ObjectToJson { public static String ObjListToJson(ArrayList<?> list){ StringBuilder build=new StringBuilder(); //迭代器 Iterator<?> iterator=list.iterator(); build.append("["); String separate=""; while(iterator.hasNext()){ build.append(separate); //object转json字符串 String str=ObjToJson(iterator.next()); build.append(str); separate=","; } build.append("]"); return build.toString(); } @SuppressWarnings("unchecked") public static String ObjToJson(Object obj){ StringBuilder build=new StringBuilder(); build.append("{"); @SuppressWarnings("rawtypes") Class cla=null; try { //反射加载类 cla=Class.forName(obj.getClass().getName()); } catch (ClassNotFoundException e) { System.out.println(obj.getClass().toString().concat(" 未找到这个类")); e.printStackTrace(); return null; } StringBuffer methodname=new StringBuffer(); //获取java类的变量 Field[] fields=cla.getDeclaredFields(); String separate=""; for(Field temp:fields){ build.append(separate); build.append("\""); build.append(temp.getName()); build.append("\":"); methodname.append("get"); methodname.append(temp.getName().substring(0,1).toUpperCase()); methodname.append(temp.getName().substring(1)); build.append("\""); Method method=null; try { //获取java的get方法 method=cla.getMethod(methodname.toString()); } catch (NoSuchMethodException | SecurityException e) { methodname.setLength(0); e.printStackTrace(); } try { //执行get方法,获取变量参数的直。 build.append(method.invoke(obj)); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } build.append("\""); methodname.setLength(0); separate=","; } build.append("}"); return build.toString(); } }
Test.java
package com.test; import java.util.ArrayList; import com.ObjectToJson.ObjectToJson; public class Test { public static void main(String[] args){ //数据构建 ArrayList<User> list=getlist(); //数据转换 String listjson=ObjectToJson.ObjListToJson((ArrayList<?>)list); System.out.println("{\"data\":"+listjson+"}"); } public static ArrayList<User> getlist(){ User user00=new User(); user00.setUserage("27"); user00.setUsername("smart"); user00.setUsersex("man"); User user01=new User(); user01.setUserage("27"); user01.setUsername("smart00"); user01.setUsersex("man"); ArrayList<User> list=new ArrayList<User>(); list.add(user00); list.add(user01); return list; } }
User.java
package com.test; public class User { private String username; private String usersex; private String userage; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUsersex() { return usersex; } public void setUsersex(String usersex) { this.usersex = usersex; } public String getUserage() { return userage; } public void setUserage(String userage) { this.userage = userage; } }
Test results
{"data":[{"username":"smart","usersex":"man","userage":"27"},{"username":"smart00","usersex":"man","userage":"27"}]}
More java reflection implementation javabean to json For articles related to example codes, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability
