直接贴代码,不说废话:
mvn配置文件pom.xml中加入:
com.google.code.gson
gson
2.8.0
非mvn可以从网址下载jar包导入即可,我在配置mvn时遇到问题,在配好且自动下载好jar 包后在代码中无法import,是因为mvn自动下载的jar 包有问题,手动下载后放到mvn的资源库目录下即可。java代码如下:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonOperater {
public static void main(String[] args) {
ReadJsonStr(defJsonStr);
}
/**
* Read JSON string demo
* @param jsonString
* @return
*/
public static void ReadJsonStr(String jsonStr)
{
//获取json对象
jsonStr = jsonStr.replace("null","\"\"");
JsonParser parser = new JsonParser();
JsonObject jsonobj = parser.parse(jsonStr).getAsJsonObject();
//JsonObject object=(JsonObject) parser.parse(new FileReader("test.json"));
//获取json属性
String name = jsonobj.get("name").getAsString();
System.out.println("name: " + name);
int age = jsonobj.get("age").getAsInt();
System.out.println("age: " + age);
boolean isgoodman = jsonobj.get("isgoodman").getAsBoolean();
System.out.println("isgoodman: " + isgoodman);
//获取json中数组
JsonArray likefoodsArray = jsonobj.get("likefoods").getAsJsonArray();
System.out.println("likefoodsArray: " + likefoodsArray);
System.out.println("likefoodsArray[0]: " + likefoodsArray.get(0));
//获取json中的json
JsonObject teachers = jsonobj.get("teachers").getAsJsonObject();
String chines = teachers.get("chines").getAsString();
System.out.println("chines: " + chines);
//获取json数组中的json
JsonArray courses = jsonobj.get("courses").getAsJsonArray();
JsonObject courses0 = courses.get(0).getAsJsonObject();
System.out.println("courses0-name: " + courses0.get("name").getAsString());
//json object to string
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String outJsonStr = gson.toJson(jsonobj);
System.out.println("outJsonStr:\n" + outJsonStr);
}
private static String defJsonStr = "{\"name\": \"XIAOMING\",\"age\": 21,\"isgoodman\": true,\"likefoods\": [\"meat1\",\"meat2\",\"meat3\",\"meat4\"],\"teachers\": {\"chines\": \"teacher1\",\"english\": \"teacher2\"},\"courses\": [{\"name\": \"chines\",\"teacher\": \"teacher1\",\"grade\": 90},{\"name\": \"english\",\"teacher\": \"teacher2\",\"grade\": 60}],\"girlfriend1\": \"\",\"girlfriend2\": null}";
/*{
"name": "XIAOMING",
"age": 21,
"isgoodman": true,
"likefoods": ["meat1","meat2","meat3","meat4"],
"teachers": {
"chines": "teacher1",
"english": "teacher2"
},
"courses": [
{
"name": "chines",
"teacher": "teacher1",
"grade": 90
},
{
"name": "english",
"teacher": "teacher2",
"grade": 60
}
],
"girlfriend1": "",
"girlfriend3": , //error
"girlfriend2": null //replace("null","")
}*/
}
有用到的粘走,路过大神多喷多指教……