将JSON对象添加到现有JSON文件 [英] Adding JSON objects to existing JSON File

查看:187
本文介绍了将JSON对象添加到现有JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我最近受命创建一个实用程序,该实用程序将允许通过gson库将JSON轻松添加到.json文件中.我已经在Kotlin中对此进行了编码:

So I've recently been tasked with creating a utility which will allow easy addition of JSON to a .json file via the gson library. I've coded this in Kotlin:

fun addObject(filePath: String, name: String, values: Array<Array<String>>) {
try {

    var writer: JsonWriter = JsonWriter(FileWriter(File(filePath)))
    writer.beginObject()
    writer.name(name)
    writer.beginObject()
    for(item in values){
        writer.name(item[0]).value(item[1])
    }
    writer.endObject()
    writer.endObject()

    writer.close()

    println("[JSONUtil] Wrote object successfully!")

} catch (e: IOException) {
    e.printStackTrace()
}
}

我使用了二维数组,以允许用户在该对象中添加具有任意数量值的不同对象.例如,您可以这样运行它:

I used a 2 Dimensional array to allow the user to add different objects with any number of values in said object. For instance, you would run it like so:

addObject("C:\\Users\\Test\\Desktop\\JsonUtility\\output.json", "GENERAL", 
arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")))

这将创建以下JSON:

This creates the following JSON:

{"GENERAL":{"POS_X":"2","POS_Y":"4"}}

这就是它的意图和工作方式,我的问题是,再次运行该函数时,它会完全覆盖文件中的先前JSON,这显然是不好的.

This is how it was intended and works, my issue is that upon running the function again it completely overwrites the previous JSON in the file, and this is obviously bad.

我的问题是:

  • 如何在整个文件内或特定位置添加新的JSON对象,例如本例中的"addObject("GENERAL",...)?

  • How can I add new JSON objects inside the entire file, or at specific points, like "addObject("GENERAL", ...)" for this example?

我该如何做得更好?

我对Kotlin还是很陌生,并且大部分时间都在使用Java进行编码,因此Java解决方案很好,因为我确信我将能够对其进行转换.

I'm fairly new to Kotlin and have been coding in Java mostly, so Java solutions are fine as I'm sure I'll be able to convert it.

提前谢谢!

新代码,不知道如何实现:

New Code, no idea how to implement it:

fun UpdateJson(path: String, name: String, value: String){
    var gson = Gson()
    var reader: FileReader = FileReader(File(path))

    val type = object : TypeToken<Map<String, String>>() {}.type
    println("Type: " + type.toString())
    println("Existing Json: ${gson.fromJson<Map<String,String>>
    (JsonReader(reader), type)}")
    var existingJson: Map<String, String> = 
    gson.fromJson<Map<String,String>>(JsonReader(reader), type)
    existingJson.put(name, value)
    FileWriter(File(path)).use({ writer -> 
    writer.write(gson.toJson(existingJson)) })
}

推荐答案

最简单的方法是按照@KrisRoofe的建议,读取json,然后添加一个元素.我可以通过转换文件中的现有json来做到这一点到地图.由于您实际上并不关心现有的json,因此您要做的就是向该Map添加一个新条目.完成此操作后,只需将新的Map写入文件.您可以这样操作:

The easiest way is to, as @KrisRoofe suggested, read the json, then add an element. I would do this by converting the existing json in the file to a Map. Since you don't actually care about the existing json, all you want to do is add a new entry to that Map. Once you do that, simply write the new Map to the File. You can do this like so:

public class UpdateJson {
    public static void main(String[] args) throws IOException {
        addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")));
    }

    private static void addObject(String fileName, String newObjName, String newObjValue) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> existingJson = gson.fromJson(new JsonReader(new FileReader(new File(fileName))), type);
        existingJson.put(newObjName, newObjValue);
        try (FileWriter writer = new FileWriter(new File(fileName))) {
            writer.write(gson.toJson(existingJson));
        }
    }

    private static String arrayOf(String s1, String s2) {
        return "[" + s1 + ", " + s2 + "]";
    }
}

上面的解决方案是Java解决方案. Kotlin中的Type似乎有问题.

The above solution is a Java solution. There seems to be an issue with the Type in Kotlin.

  1. 堆栈溢出问题有一种解决方法通过使用object:
  2. 此外,请注意,根据 Kotlin,要将Kotlin与反射一起使用,您需要一个单独的jar文档'
  1. This Stack Overflow question has a workaround by using object:
  2. Also, note that to use reflection with Kotlin, you need a separate jar, according to Kotlin documentation'

科特林提供的答案:

fun main(args: Array<String>) {
    addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X", "2"), arrayOf("POS_Y", "4")))
}


fun addObject(path: String, name: String, value: String) {
    val gson = Gson()
    val reader: FileReader = FileReader(File(path))
    val type = object : TypeToken<Map<String, String>>() {}.type
    System.out.println("Type: " + type.toString())
    val existingJson = gson.fromJson<Map<String, String>>(JsonReader(reader), type)
    System.out.println("Existing Json: ${existingJson}")
    val newJsonMap = existingJson.plus(Pair(name, value))
    FileWriter(File(path)).use(
        { writer -> writer.write(gson.toJson(newJsonMap)) }
    )
}

fun arrayOf(s1: String, s2: String): String {
    return "[$s1, $s2]"
}

这篇关于将JSON对象添加到现有JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆