こんにちは、私のJsonパーサーの何が問題になっているのかを見つけるのに問題があります。
こんにちは、オブジェクトの学生がいます(ID、Name、Grade)これが私のドキュメントに学生を書く方法です:public void run(){
System.out.println("Server get:" + value);
Gson gson = new Gson();
System.out.println("this record will be created in the source document");
String json = gson.toJson(value);
// System.out.println(json);
//2. Convert object to JSON string and save into a file directly
try (FileWriter writer = new FileWriter(File,true)) {
gson.toJson(value, writer);
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
}
ドキュメントでは、{"SID": "fd36ac24-4487-49aa-bdd0-40535b55d081"、 "Name": "Marie"、 "Major": "IT"}
これは良い学生オブジェクトです。そして今、私はこのファイル情報を再び学生オブジェクトに取得したいと思います。これは私がそれをやろうとする方法です:
public Student Creation_Two() {
String fichier ="C:\\Users\\programming\\Personne_source.txt";
Student s1 = new Student();
Gson gson = new Gson();
System.out.println("we try to parse the document with json to the object");
JsonReader reader = new JsonReader(new StringReader(fichier));
reader.setLenient(true);
System.out.println("reader value "+reader);
try
{
s1 = gson.fromJson(reader, Student.class);
System.out.println(s1 +" s1 have been serialized");
return s1;
}
catch (IllegalStateException | JsonSyntaxException e1)
{
System.out.println("error in getting the object");
e1.printStackTrace();
}
return s1;
}
しかし、それは機能しませんでした。エラーが発生しました:BEGIN_OBJECTが必要ですが、1行2列目がSTRINGでした。
こちらが学生クラスです
public class Student {
private static final long serialVersionUID = 1L;
private String SID;
private String Name;
private String Major;
public Student(String SID, String Name, String Major)
{
this.setSID(SID);
this.setName(Name);
this.setMajor(Major);
}
public Student() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Student SID= " + SID + ", Name= " + Name + ", Major= " + Major + "";
}
//all the get set
これで試してください:
Gson gson = new Gson();
System.out.println("this record will be created in the source document");
String fichier ="C:\\Users\\programming\\Personne_source.txt";
byte[] encoded =Files.readAllBytes(Paths.get(fichier));
System.out.println("JSON: " + new String(encoded, "UTF-8"));
Student s1 = new Student();
try
{
s1 = gson.fromJson(new String(encoded, "UTF-8"), Student.class);
System.out.println(s1 +" s1 have been serialized");
}
catch (IllegalStateException | JsonSyntaxException e1)
{
System.out.println("error in getting the object");
e1.printStackTrace();
}
System.out.println(s1.toString());
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加