Java:如何使用GSON创建此JSON数组结构

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

Java: How do I create this JSON Array Structure using GSON

问题

{
   "user":[
      {
         "name":"user1",
         "email":"user1@gmail"
      },
      {
         "name":"user2",
         "email":"user2@gmail"
      }
   ]
}
public void appendToObject(File jsonFile, String key, String value) {
    Objects.requireNonNull(jsonFile);
    Objects.requireNonNull(key);
    Objects.requireNonNull(value);
    if (jsonFile.isDirectory()) {
        throw new IllegalArgumentException("File can not be a directory!");
    }
    try {
        JsonObject node = readOrCreateNew(jsonFile);
        JsonArray userArray = new JsonArray();
        userArray.add(user(key, value));
        node.add("user", userArray);

        try (FileWriter writer = new FileWriter(jsonFile)) {
            gson.toJson(node, writer);
        }

    } catch (Exception e) {
        Log.d("display1", "appendToObject: error" + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

private JsonObject user(String name, String email) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", name);
    jsonObject.addProperty("email", email);
    return jsonObject;
}

private JsonObject readOrCreateNew(File jsonFile) throws IOException {
    if (jsonFile.exists() && jsonFile.length() > 0) {
        try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
            return gson.fromJson(reader, JsonObject.class);
        }
    }
    return new JsonObject();
}

When properly structured, the JSON output will match the desired structure as shown above.

英文:

I want to create a JSON array structure like this or append an object to the structure

{ "user" : [
     {"name" : "user1", "email": "user1@gmail"},
     {"name": "user2", "email": "user2@gmail"}
   ]
}

I'm using GSON to write this into a file

    public void appendToObject(File jsonFile, String key, String value)  {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}

Here's the code with suggestions integrated and with reading and writing JSON file functions

but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}

how to structure it so that I get the desired output

答案1

得分: 2

我在 `appendToObject` 中省略了部分代码但意思应该是清楚的

``` java

  public void appendToObject(File jsonFile, String key, String value)  {

    ...

    JsonObject node = readOrCreateNew(jsonFile);
  
    JsonObject newUser = user(key, value);
    JsonElement user = node.get("user");
    
    if (user != null && user.isJsonArray()){
      ((JsonArray) user).add(newUser);
    } else {
      JsonObject root = new JsonObject();
      node.add("user", createUserArray(newUser));
    }
     
    ...
  }

  private JsonObject createUserArray(JsonObject ... objects){
    JsonArray userArray = new JsonArray();
    for (JsonObject user : objects) {
      userArray.add(user);
    }
    return userArray;
  }

  private JsonObject user(String email, String name){
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", name);
    jsonObject.addProperty("email", email);
    return jsonObject;
  }

英文:

I omitted some your code in appendToObject. But the meaning should be clear.


  public void appendToObject(File jsonFile, String key, String value)  {

    ...

    JsonObject node = readOrCreateNew(jsonFile);
  
    JsonObject newUser = user(key, value);
    JsonElement user = node.get("user");
    
    if (user != null && user.isJsonArray()){
      ((JsonArray) user).add(newUser);
    } else {
      JsonObject root = new JsonObject();
      node.add("user", createArray(newUser));
    }
     
    ...
  }

  private JsonObject createUserArray(JsonObject ... objects){
    JsonArray userArray = new JsonArray();
    for (JsonObject user : objects) {
      userArray.add(user);
    }
    return userArray;
  }

  private JsonObject user(String email, String name){
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", name);
    jsonObject.addProperty("email", email);
    return jsonObject;
  }

huangapple
  • 本文由 发表于 2020年10月6日 02:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64213914.html
匿名

发表评论

匿名网友

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

确定