JSON, as a lightweight data exchange tool, is very convenient to use. However, when interacting with the J2EE background, you need to directly convert JSON into Java persistent objects in our project for business operations or direct persistence to the database. There are many such data conversion tools. The third package of JSON-tool is used in our project. The steps are as follows:
1. Accept foreground JSON data
String data = request. getparameter ("data ");
2. Construct a jsonobject or a jsonarray through the received JSON data
Jsonobject JSON = new jsonobject (data );
3. Use the tojava () method of jsonmapper to convert jsonobject to the desired object.
However, in the process of processing, if it is difficult to handle the association between the primary and Foreign keys, it is prone to errors, so I thought of the reflection Based on Java
Mechanism to dynamically convert a JSON object to a pojo object.
Private object fromjsontojava (jsonobject JSON, class pojo)
Throws exception {
// Obtain the fields defined by pojo.
Field [] fields = pojo. getdeclaredfields ();
// Dynamically generate a pojo object based on the input class
Object OBJ = pojo. newinstance ();
For (field: fields ){
// Set the field to be accessible (required; otherwise, an error is returned)
Field. setaccessible (true );
// Obtain the attribute name of the field.
String name = field. getname ();
// The purpose of this section is to throw an exception if the field does not exist in the jsonobject. If an exception occurs, it is skipped.
Try {
JSON. Get (name );
} Catch (exception ex ){
Continue;
}
If (JSON. Get (name )! = NULL &&! "". Equals (JSON. getstring (name ))){
// Convert the value to the corresponding type based on the field type and set it to the generated object.
If (field. GetType (). Equals (long. Class) | field. GetType (). Equals (long. Class )){
Field. Set (OBJ, stringutil. parselong (JSON. getstring (name )));
} Else if (field. GetType (). Equals (string. Class )){
Field. Set (OBJ, JSON. getstring (name ));
} Else if (field. GetType (). Equals (double. Class) | field. GetType (). Equals (double. Class )){
Field. Set (OBJ, stringutil. parsedouble (JSON. getstring (name )));
} Else if (field. GetType (). Equals (integer. Class) | field. GetType (). Equals (Int. Class )){
Field. Set (OBJ, stringutil. parseint (JSON. getstring (name )));
} Else if (field. GetType (). Equals (Java. util. Date. Class )){
Field. Set (OBJ, datetimeutil. stringtodate (JSON. getstring (name), "yyyy-mm-dd "));
} Else {
Continue;
}
}
}
Return OBJ;
}