目的
{ "Last Access" : "2020/3/35", "value" : [ { "Time" : "2020/3/24", "sentence" : "kosuei", "bunsyou" : "こうせい" }, { "Time" : "2020/3/25", "sentence" : "The exsecutive meeting took placed last night.", "bunsyou" : "昨夜、役員会議が開かれました" } ] }
こんな感じのJsonファイルを作りたいで。
現状
java
1class UserData{ 2 public String date; 3 public String sentence; 4 public String bunsyou; 5 6 UserData(String date,String sentence,String bunsyou){ 7 this.date = date; 8 this.sentence = sentence; 9 this.bunsyou = bunsyou; 10 } 11} 12 13 14public class JsonTry2{ 15 public static String date; 16 JsonTry2(){ 17 Calendar cal = Calendar.getInstance(); 18 int y = cal.get(Calendar.YEAR); 19 int m = cal.get(Calendar.MONTH); 20 int d = cal.get(Calendar.DATE); 21 date = y+"/"+m+"/"+d; 22 } 23 24 public static void main(String[] args){ 25 File per = new File("Sample.json"); 26 File memo = new File("UserData.json"); 27 UserData data1 = new UserData(JsonTry2.date,"I am a hero","私はヒーローです"); 28 UserData data2 = new UserData(JsonTry2.date,"The exsecutive meeting took placed last night.","昨夜、役員会議が開かれました"); 29 List<UserData> uDatas = Arrays.asList(data1,data2); 30 31 ObjectMapper mapper = new ObjectMapper() 32 .enable(SerializationFeature.INDENT_OUTPUT); 33 ObjectNode root = mapper.createObjectNode(); 34 ArrayNode array = mapper.createArrayNode(); 35 36 try{ 37 JsonNode tree = mapper.readTree(per); 38 ObjectNode item = mapper.createObjectNode(); 39 ObjectNode format = mapper.createObjectNode(); 40 format.put("Last Access",JsonTry2.date); 41 for (UserData ud :uDatas){ 42 item.put("Time",ud.date); 43 item.put("sentence",ud.sentence); 44 item.put("bunsyou",ud.bunsyou); 45 } 46 array.add(tree); 47 array.add(item); 48 root.set("value",array); 49 mapper.writeValue(memo,root); 50 }catch(IOException e){ 51 e.printStackTrace(); 52 } 53 } 54}
こんな感じにプログラムを作って
{ "value" : [ { "Time" : "2020/3/24", "sentence" : "kosuei", "bunsyou" : "こうせい" }, { "Time" : "2020/3/25", "sentence" : "The exsecutive meeting took placed last night.", "bunsyou" : "昨夜、役員会議が開かれました" } ] }
ここまでできました。
#質問
最後に"Last Access" : "2020/3/35",
を追加するために、root.set("Last Access","2020/3/25")
ってやればいいのかなと思ったのですが、2020/3/35
の部分はJsonNode型
にしなくてはいけません。いろいろ探したのですがStringをJsonNodeに変換するものはなく、どうしてもできません。
どうやったら、Last Access" : "2020/3/35
これを追加できますか?
あなたの回答
tips
プレビュー