简体   繁体   English

GsonFromJson:如何使用数组结构进行序列化和反序列化

[英]GsonFromJson: how to serialize and de serialize with array structures

Im working on a project where we used jsonfile as its database since SQLite doesnt meet the requirement. 我正在一个项目中工作,我们使用jsonfile作为其数据库,因为SQLite不满足要求。 The project has a portion when an object fron the wordbank is use it will change the status(such as 1-4). 当使用单词库中的某个对象时,项目中会有一部分会更改状态(例如1-4)。 I made use of JSONArray to access the data. 我利用JSONArray来访问数据。 When i tried to change/edit the status, it doesnt save or write back to the jsonfile. 当我尝试更改/编辑状态时,它不会保存或写回jsonfile。 Instead it only works on the momentary use of the application. 相反,它仅适用于应用程序的瞬时使用。

From searches, alot of stuff pop out that using gson. 通过搜索,使用gson弹出了很多东西。 I concluded to use gson. 我总结使用gson。

I am new to gson and just started learning it the other day. 我是gson的新手,几天前才开始学习它。 And i am having troubles with it. 而且我有麻烦。

This is the structure of my jsonfile. 这是我的jsonfile的结构。 It has 2 objects(users and wordbank) that are arrayed 它有2个对象(用户和字库)排列

{ 
"users" :
  [{
    "username": "free",
    "password": "free",
    "email": "free@gmail.com",
    "type": "1"
  },
  {
    "username": "premium",
    "password": "premium",
    "email": "premium@gmail.com",
    "type": "2"
  }],
"wordbank" : 
  [{
      "English": "able",
      "Cebuano": "kaya",
      "Pronunciation": "ká-ya",
      "POS": "adjective",
      "Audio": "kaya.mp3",
      "Status": "0"
  },
  {
      "English": "advice",
      "Cebuano": "tambag",
      "Pronunciation": "tam-bag",
      "POS": "noun",
      "Audio": "tambag.mp3",
      "Status": "0"
  }]
}

From what I've seen in tutorial videos is that you create a different java class for its model. 从教程视频中我看到的是,您为其模型创建了一个不同的Java类。 So i create 3 java class. 所以我创建了3个Java类。 user, wordbank and dictionary (combining them both). 用户,单词库和字典(将它们结合在一起)。

public class dictionary{
  users[] user;
  wordbanks[] word;
}

Im using an existing jsonfile already so i parsed it and got its jsonstring. 我已经使用了现有的jsonfile,所以我解析了它并得到了jsonstring。 After which i tried to deserialize it using 之后,我尝试使用反序列化

jsonstring = readFromFile();//returns string from jsonfile
dictionary list = new Gson().fromJson(jsonstring, dictionary.class);

runned it and debug it. 运行并调试它。 but when i got the results. 但是当我得到结果时。 it was null. 它为空。

QUESTIONS: 1.Will I be able to edit and save the changes in json file by using gson? 问题:1.是否可以使用gson编辑并保存json文件中的更改? 2.Is my structure correct for the distionary class? 2.我的结构是否适合应修课程? 3.how to serialize and deserialize it? 3.如何序列化和反序列化它?

  • If your member variables of pojo Classes(users,workdbank,dictionary) don't match with JSON key, consider using @SerializedName provided by GSON. 如果您的pojo类的成员变量(用户,workdbank,字典)与JSON键不匹配,请考虑使用GSON提供的@SerializedName。 In your case, i was able to deserialise the string using gson by using @SerializedName as shown below 在您的情况下,我可以通过使用@SerializedName来使用gson反序列化字符串,如下所示

User Class 用户类别

 public class User {

       @SerializedName("username")
    private String userName;
    @SerializedName("password")
    private String password;
    @SerializedName("email")
    private String email;
    @SerializedName("type")
    private String type;

    // Add Getters and Setters
}

WordBank Class 词库类

public class Wordbank {

    @SerializedName("English")
    private String english;
    @SerializedName("Cebuano")
    private String cebuano;
    @SerializedName("Pronunciation")
    private String pronunciation;
    @SerializedName("POS")
    private String pos;
    @SerializedName("Audio")
    private String audio;
    @SerializedName("Status")
    private String status;

    // Add getters and Setters
}

Dictionary Class 字典类

    public class Dictonary {

    @SerializedName("users")
    User[] userArray;
    @SerializedName("wordbank")
    Wordbank[] wordbankArray;

    public User[] getUserArray() {
        return userArray;
    }

    public void setUserArray(User[] userArray) {
        this.userArray = userArray;
    }

    public Wordbank[] getWordbankArray() {
        return wordbankArray;
    }

    public void setWordbankArray(Wordbank[] wordbankArray) {
        this.wordbankArray = wordbankArray;
    }
}

After making necessary changes as explained above, I was able to deserialise the string 如上所述进行必要的更改后,我可以反序列化字符串

 Dictonary dictonary =  new Gson().fromJson(input,Dictonary.class);

Yes you can use Gson for all your requirements. 是的,您可以使用Gson满足所有要求。 First create matching Pojo for your json structure. 首先为您的json结构创建匹配的Pojo。 you can use tools such as this pojo generator . 您可以使用诸如pojo生成器之类的工具。 Just paste the json there (don't select json schema) and generate. 只需将json粘贴到那里(不要选择json模式)并生成即可。 Assuming you have three classes Result (contains to lists, similar to your dictionary class), User and Wordbank class. 假设您有三个类Result (包含在列表中,类似于字典类), UserWordbank类。 You can read (deserialize) and write (serialize) back into a file as follows. 您可以按以下方式读取(反序列化)和写入(序列化)回文件。

try {
    // deserialize
    Result result = gson.fromJson(new FileReader(new File("src/test/resources/sample.json")), Result.class);
    // ... update result as required
    // result.users.remove(0);
    // serialize
    String json = gson.toJson(result);
    Files.write(new File("src/test/resources/sample.json").toPath(), json.getBytes());
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM