Java Reflection Implementation JavaBean turn JSON instance code _java

Source: Internet
Author: User
Tags reflection stringbuffer

Objecttojson.java

Copy Code code as follows:

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 ();
Iterators
Iterator<?> Iterator=list.iterator ();
Build.append ("[");
String separate= "";
while (Iterator.hasnext ()) {
Build.append (separate);
object to JSON string
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 {
Reflection Load Class
Cla=class.forname (Obj.getclass (). GetName ());
catch (ClassNotFoundException e) {
System.out.println (Obj.getclass (). toString (). Concat ("No such class found");
E.printstacktrace ();
return null;
}

StringBuffer methodname=new StringBuffer ();
Get variables for Java classes
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 {
Getting Java Get methods
Method=cla.getmethod (Methodname.tostring ());
catch (Nosuchmethodexception | SecurityException e) {
Methodname.setlength (0);
E.printstacktrace ();
}

try {
Executes the Get method, obtaining the straight of the variable parameter.
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

Copy Code code as follows:

Package com.test;

Import java.util.ArrayList;

Import com. Objecttojson.objecttojson;

public class Test {
public static void Main (string[] args) {
Data construction
Arraylist<user> list=getlist ();
Data conversion
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

Copy Code code as follows:

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

Copy Code code as follows:

{"Data": [{"username": "smart", "Usersex": "Man", "Userage": "The"},{"username": "smart00", "Usersex": "Man", "Userage": " 27 "}]}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.