Javaで既存のJSONファイルにJSON文字列を追加するにはどうすればよいですか?
Gson はJava用のjsonライブラリであり、JSONの生成に使用できます。最初のステップでは、JSONファイルを読み取ってJavaオブジェクトに解析し、型キャストする必要があります。 JSonObjectへのJavaオブジェクト JsonArrayに解析します 。次に、このJSON配列を繰り返して、 JSONElementを出力します。 。 JsonWriterを作成できます JSONでエンコードされた値を一度に1つのトークンでストリームに書き込むクラス。最後に、新しいJSON文字列を既存のjsonファイルに書き込むことができます。
例
import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.stream.*;
import com.google.gson.annotations.*;
public class JSONFilewriteTest {
public static String nameRead;
public static void main(String[] args) {
try {
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("employee1.json"));
JsonObject jsonObject = (JsonObject) obj;
System.out.println("The values of employee1.json file:\n" + jsonObject);
JsonArray msg = (JsonArray)jsonObject.get("emps");
Iterator<JsonElement> iterator = msg.iterator();
while(iterator.hasNext()) {
nameRead = iterator.next().toString();
System.out.println(nameRead);
}
Name name = new Name();
name.setName("Vamsi");
Gson gson = new Gson();
String json = gson.toJson(name);
FileWriter file = new FileWriter("employee1.json", false);
JsonWriter jw = new JsonWriter(file);
iterator = msg.iterator();
Employees emps = new Employees();
while(iterator.hasNext()) {
emps.addEmployee(gson.fromJson(iterator.next().toString(), Name.class));
}
emps.addEmployee(name);
gson.toJson(emps, Employees.class, jw);
file.close();
System.out.println("data added to an existing employee1.json file successfully");
} catch(Exception e) {
e.printStackTrace();
}
}
}
// Name class
class Name {
@Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// Employees class
class Employees {
@Expose
List<Name> emps = new ArrayList<>();
public List<Name> getEmployees() {
return emps;
}
public void addEmployee(Name name) {
this.emps.add(name);
}
} 出力
The values of employee1.json file:
{"emps":[{"name":"Adithya"},{"name":"Jai"}]}
{"name":"Adithya"}
{"name":"Jai"}
data added to an existing employee1.json file successfully
-
JavaでJSONオブジェクトをファイルに書き込むにはどうすればよいですか?
JSON 広く使用されているデータ交換の1つです フォーマットし、軽量 および言語 独立 。 json.simple は、JSONファイルの書き込みに使用できる軽量のJSON処理ライブラリです。 エンコードに使用できます またはデコード JSONテキストであり、 Jに完全に準拠しています SON仕様(RFC4627)。 JSONファイルを読み取るには、 json-simple.jarをダウンロードする必要があります ファイルを作成し、それを実行するためのパスを設定します。 例 import java.io.*; import java.util.*; import org.json.s
-
Javaを使用してJSONファイルを作成/作成する方法は?
JSONまたはJavaScriptObjectNotationは、人間が読める形式のデータ交換用に設計された、軽量のテキストベースのオープンスタンダードです。 JSONで使用される規則は、C、C ++、Java、Python、Perlなどを含むプログラマーに知られています。サンプルJSONドキュメント − { "book": [ { "id": "01",