我知道一些JSON库,我现在正在研究Google-JSON,但我想要实现的只是简单的事情,我想知道你会建议什么.
我想要一个JSON库,让我读取一个JSON文本文件,让我把它转换成字符串,int,boolean等. - 现在使用Json.org/java
它可以阅读!但!!
import org.json.*;
public class readJ {
public static String MapTitle;
public static int[][] tiles;
public static void main(String[] args) {
String json =
"{"
+"'name': 'map_one.txt',"
+"'title': 'Map One',"
+"'currentMap': 4,"
+"'items': ["
+"{ name: 'Pickaxe', x: 5, y: 1 },"
+"{ name: 'Battleaxe', x: 2, y: 3 }"
+"],"
+"map': [ [ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
+"[ 1,3,1,1,1,24,1,1,1,1,1,1,1 ],"
+"[ 1,7,1,1,1,24,1,1,24,1,1,1,1 ],"
+"[ 1,7,1,1,7,1,1,1,24,1,1,1,1 ],"
+"[ 1,7,7,7,1,24,24,24,24,1,1,1,1 ],"
+"[ 1,1,7,1,1,24,1,24,1,1,1,1,1 ],"
+"[ 1,1,1,1,1,24,1,1,1,1,1,1,1 ],"
+"[ 1,1,3,1,1,24,1,1,1,1,1,1,1 ],"
+"[ 1,3,3,1,1,24,1,1,1,1,1,1,1 ]]"
+"}";
try {
JSONObject JsonObj = new JSONObject(json);
MapTitle = JsonObj.getString("title");
tiles = JsonObj.getJSONArray("map");
}catch (JSONException er) {
er.printStackTrace();
}
System.out.println(MapTitle);
System.out.println(tiles[0][1]);
}
}
Run Code Online (Sandbox Code Playgroud)
编译时我收到此错误:
C:\Users\Dan\Documents\readJSON\readJ.java:32: incompatible types
found : org.json.JSONArray
required: int[][]
tiles = JsonObj.getJSONArray("map");
^
1 error
Tool completed with exit code 1
Run Code Online (Sandbox Code Playgroud)
安装Google Gson并创建这两个模型类
public class Data {
private String name;
private String title;
private int currentMap;
private List<Item> items;
private int[][] map;
public String getName() { return name; }
public String getTitle() { return title; }
public int getCurrentMap() { return currentMap; }
public List<Item> getItems() { return items; }
public int[][] getMap() { return map; }
public void setName(String name) { this.name = name; }
public void setTitle(String title) { this.title = title; }
public void setCurrentMap(int currentMap) { this.currentMap = currentMap; }
public void setItems(List<Item> items) { this.items = items; }
public void setMap(int[][] map) { this.map = map; }
}
Run Code Online (Sandbox Code Playgroud)
和
public class Item {
private String name;
private int x;
private int y;
public String getName() { return name; }
public int getX() { return x; }
public int getY() { return y; }
public void setName(String name) { this.name = name; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
Run Code Online (Sandbox Code Playgroud)
并按如下方式转换 JSON:
Data data = new Gson().fromJson(json, Data.class);
Run Code Online (Sandbox Code Playgroud)
要获得标题,只需执行以下操作:
System.out.println(data.getTitle()); // Map One
Run Code Online (Sandbox Code Playgroud)
并获取 x=3 和 y=3 处的地图项:
System.out.println(data.getMap()[3][3]); // 1
Run Code Online (Sandbox Code Playgroud)
并获取第一个的名称Item:
System.out.println(data.getItems().get(0).getName()); // Pickaxe
Run Code Online (Sandbox Code Playgroud)
简单的!使用其他方式转换也很简单Gson#toJson()。
String json = new Gson().toJson(data);
Run Code Online (Sandbox Code Playgroud)
另请参阅此答案以了解另一个复杂的 Gson 示例。