使用Java(Gson)从Json中读取对象

huangapple go评论82阅读模式
英文:

Read object from Json with Java (gson)

问题

以下是你要翻译的内容:

我在Json文件中读取对象时遇到了问题。我尝试将其视为ArrayList、作为Object处理,但由于返回null,我不知道还能尝试什么。我该如何从对象中获取项?

导入:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.*;

Json文件:

{
	"letters": 4,
	"numbers": 4,
	"positions": 4,
	"id":[[-1,0],[0,1],[1,0],[0,-1]],
	"wall":{
		"(0,0)":{"value":0,"walls": [false,true,true,false]},
		"(1,2)":{"value":0,"walls": [false,false,false,true]},
		"(5,7)":{"value":0,"walls": [false,true,false,false]},
		"(0,3)":{"value":0,"walls": [false,false,true,true]},
		"(2,8)":{"value":0,"walls": [true,false,true,false]}
	}
}

Java代码:

public static void readJson(String path) {
		
		Gson gson = new Gson();
		String file_gson = "";
		
		try(BufferedReader br = new BufferedReader(new FileReader(path))){
			String line;
			while((line = br.readLine()) != null) {
				file_gson += line;	
			}
			Fich element = gson.fromJson(file_gson, Fich.class);
			System.out.println(element.letters);

		}catch(FileNotFoundException ex) {
			System.out.println("");
		}catch(IOException ex) {
			System.out.println("");
		}
	}

但在对象类(Walls)中它没有将其读取给我。如果我将(walls)作为字符串放入其中会报错。

public class Fich{
	public int letters;
	public int numbers;
	public int positions;
	public ArrayList id;
	public Walls walls;
	
	
	public Fich(int letters, int numbers, Walls walls){
		this.letters = letters;
		this.letters = letters;
	}
}
英文:

I have a problem reading the object in the Json file. I have tried treating it as an ArrayList, as an Object and I don't know what else to try because it gives me null. How can I get the items out of the object?

Imports

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.*;

Json file

{
	"letters": 4,
	"numbers": 4,
	"positions": 4,
	"id":[[-1,0],[0,1],[1,0],[0,-1]],
	"wall":{
		"(0,0)":{"value":0,"walls": [false,true,true,false]},
		"(1,2)":{"value":0,"walls": [false,false,false,true]},
		"(5,7)":{"value":0,"walls": [false,true,false,false]},
		"(0,3)":{"value":0,"walls": [false,false,true,true]},
		"(2,8)":{"value":0,"walls": [true,false,true,false]}
	}
}

Java code

public static void readJson(String path) {
		
		Gson gson = new Gson();
		String file_gson = "";
		
		try(BufferedReader br = new BufferedReader(new FileReader(path))){
			String line;
			while((line = br.readLine()) != null) {
				file_gson += line;	
			}
			Fich element = gson.fromJson(file_gson, Fich.class);
			System.out.println(element.letters);

		}catch(FileNotFoundException ex) {
			System.out.println("");
		}catch(IOException ex) {
			System.out.println("");
		}
	}

But in the object class (Walls) it doesn't read it to me. And it gives me an error if I put (walls) as string.

public class Fich{
	public int letters;
	public int numbers;
	public int positions;
	public ArrayList id;
	public Walls walls;
	
	
	public Fich(int letters, int numbers, Walls walls){
		this.letters = letters;
		this.letters = letters;
	}
}

答案1

得分: 1

id字段是一个包含另一个JSON ArrayJSON Array。您可以将其映射为List<List<Integer>>wall字段是一个JSON Object,其中键是String,值是另一个JSON Object。您可以将其映射为Map<String, Wall>

以下是示例代码:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class GsonApp {

    public static void main(String[] args) throws IOException {
        Path pathToJson = Paths.get("./resource/test.json");
        Gson gson = new GsonBuilder().create();
        try (BufferedReader reader = Files.newBufferedReader(pathToJson)) {
            Fich fich = gson.fromJson(reader, Fich.class);
            System.out.println(fich);
        }
    }
}

class Fich {
    private int letters;
    private int numbers;
    private int positions;
    private List<List<Integer>> id;
    private Map<String, Wall> wall;

    // getters, setters, toString
}

class Wall {
    private int value;
    private List<Boolean> walls;

    // getters, setters, toString
}

上述代码输出:

Fich[letters=4, numbers=4, positions=4, id=[[-1, 0], [0, 1], [1, 0], [0, -1]], wall={(0,0)=Wall[value=0, walls=[false, true, true, false]], (1,2)=Wall[value=0, walls=[false, false, false, true]], (5,7)=Wall[value=0, walls=[false, true, false, false]], (0,3)=Wall[value=0, walls=[false, false, true, true]], (2,8)=Wall[value=0, walls=[true, false, true, false]]}]
英文:

id field is an JSON Array which contains another JSON Array-s. You can map it to List&lt;List&lt;Integer&gt;&gt;. wall field is a JSON Object where keys are String-s and values are another JSON Object-s. You can map it to Map&lt;String, Wall&gt;.

See below example:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class GsonApp {

	public static void main(String[] args) throws IOException {
		Path pathToJson = Paths.get(&quot;./resource/test.json&quot;);
		Gson gson = new GsonBuilder().create();
		try (BufferedReader reader = Files.newBufferedReader(pathToJson)) {
			Fich fich = gson.fromJson(reader, Fich.class);
			System.out.println(fich);
		}
	}
}

class Fich {
	private int letters;
	private int numbers;
	private int positions;
	private List&lt;List&lt;Integer&gt;&gt; id;
	private Map&lt;String, Wall&gt; wall;

	// getters, setters, toString
}

class Wall {
	private int value;
	private List&lt;Boolean&gt; walls;

	// getters, setters, toString
}

Above code prints:

Fich[letters=4, numbers=4, positions=4, id=[[-1, 0], [0, 1], [1, 0], [0, -1]], wall={(0,0)=Wall[value=0, walls=[false, true, true, false]], (1,2)=Wall[value=0, walls=[false, false, false, true]], (5,7)=Wall[value=0, walls=[false, true, false, false]], (0,3)=Wall[value=0, walls=[false, false, true, true]], (2,8)=Wall[value=0, walls=[true, false, true, false]]}]

huangapple
  • 本文由 发表于 2020年10月12日 01:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64307095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定