JSON string to Java object There are a lot of tools to use, the following small example is just my practicing
Copy Code code as follows:
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Com.jfinal.kit.JsonKit;
public class Jsontojavaobject {
public static void Main (string[] args) {
Object O1 = Parse ("{\" aa\ ": 123,cc:[1,2,3,4,{cd:f,bb:234}]}");
System.out.println (Jsonkit.tojson (O1));
}
public static Object Parse (String JSON) {
if (JSON = = null) {
return null;
}
JSON = Json.trim ();
if ("string". Equals (typeof (JSON)) {
return JSON;
}
if ("Map". Equals (typeof (JSON)) {
Return Parsemap (JSON);
}
if ("List". Equals (typeof (JSON)) {
Return Parselist (JSON);
}
return null;
}
public static Map Parsemap (String json) {
if (!) Map '. Equals (typeof (JSON)) {
throw new RuntimeException ("JSON is not a map type");
}
Map r = new HashMap ();
Parsetoken (R,json,null);
return R;
}
public static List Parselist (String json) {
if (!) List '. Equals (typeof (JSON)) {
throw new RuntimeException ("JSON is not a list type");
}
List r = new ArrayList ();
Parsetoken (NULL, JSON, R);
return R;
}
public static string typeof (String json) {
if (json.length () = = 0) return "string";
if (' {' ==json.charat (0)) {
if ('} ' = = Json.charat (Json.length ()-1)) {
return "Map";
}
}
if (' [' ==json.charat (0)) {
if ('] ' ==json.charat (Json.length ()-1)) {
return "List";
}
}
Return "string";
}
private static void Parsetoken (Map R, String json,list R2) {
Boolean syh = true; Double quotes
Boolean dyh = true;//Single quotation mark
Boolean DKH = true;//curly Brace
Boolean Zkh = true;//bracket
Boolean IsKey = true;
StringBuffer key = new StringBuffer ();
StringBuffer value = new StringBuffer ();
for (int i=1;i<json.length () -1;i++) {
CHAR item = Json.charat (i);
if (Dyh&&syh&&zkh) if (' {' = Item | | '} ' = = Item} {
DKH =!dkh;
}
if (DYH&&SYH&&DKH) if (' [] = Item | | '] ' = (item) {
Zkh =!zkh;
}
if (Dyh&&dkh&&zkh) if (' "= Item) {
Syh =!syh;
Continue
}
if (Syh&&dkh&&zkh) if (syh) if (' \ ' = Item) {
Dyh =!dyh;
Continue
}
if (Dyh&&syh&&dkh&&zkh) if (r2==null) if (dyh) if (': ' ==item) {
IsKey = false;
Continue
}
if (Dyh&&syh&&dkh&&zkh) if (', ' ==item ') {
IsKey = true;
if (r!= null) {
R.put (Key.tostring (), Parse (value.tostring ()));
}
if (R2!= null) {
R2.add (Parse (key.tostring ()));
}
Key = new StringBuffer ();
Value = new StringBuffer ();
Continue
}
if (IsKey) {
Key.append (item);
}else{
Value.append (item);
}
}
if (!key.tostring (). Trim (). Equals ("")) {
if (r!= null) {
if (value.tostring (). Trim (). Equals ("")) throw new RuntimeException ("JSON format error");
R.put (Key.tostring (), Parse (value.tostring ()));
}
if (R2!= null) {
R2.add (Parse (key.tostring ()));
}
}
}
}
Console output
Copy Code code as follows:
{"AA": "123", "CC": ["1", "2", "3", "4", {"BB": "234", "CD": "F"}]}