fix: Video.toString() outputs an illegal json string (#3032)

refactor: json string concat

add an extra line at EOF
This commit is contained in:
Xcyq
2024-10-06 14:54:41 +08:00
committed by GitHub
parent 8bd31758b9
commit 24b4586944
3 changed files with 20 additions and 9 deletions
@@ -25,6 +25,7 @@
package com.iluwatar.partialresponse;
import java.lang.reflect.Field;
import java.util.StringJoiner;
/**
* Map a video to json.
@@ -39,18 +40,15 @@ public class FieldJsonMapper {
* @return json of required fields from video
*/
public String toJson(Video video, String[] fields) throws Exception {
var json = new StringBuilder().append("{");
var json = new StringJoiner(",", "{", "}");
var i = 0;
var fieldsLength = fields.length;
while (i < fieldsLength) {
json.append(getString(video, Video.class.getDeclaredField(fields[i])));
if (i != fieldsLength - 1) {
json.append(",");
}
json.add(getString(video, Video.class.getDeclaredField(fields[i])));
i++;
}
json.append("}");
return json.toString();
}
@@ -43,7 +43,7 @@ public record Video(Integer id, String title, Integer length, String description
+ "\"length\": " + length + ","
+ "\"description\": \"" + description + "\","
+ "\"director\": \"" + director + "\","
+ "\"language\": \"" + language + "\","
+ "\"language\": \"" + language + "\""
+ "}";
}
}