#631 - Partial Response : Implement Field to json conversion
This commit is contained in:
@@ -24,6 +24,8 @@
|
||||
|
||||
package com.iluwatar.partialresponse;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
/**
|
||||
* Map a video to json
|
||||
*/
|
||||
@@ -34,7 +36,25 @@ public class FieldJsonMapper {
|
||||
* @param fields fields information to get
|
||||
* @return json of required fields from video
|
||||
*/
|
||||
public String toJson(Video video, String[] fields) {
|
||||
return null;
|
||||
public String toJson(Video video, String[] fields) throws Exception {
|
||||
StringBuilder json = new StringBuilder().append("{");
|
||||
|
||||
for (int i = 0, fieldsLength = fields.length; i < fieldsLength; i++) {
|
||||
json.append(getString(video, Video.class.getDeclaredField(fields[i])));
|
||||
if (i != fieldsLength - 1) {
|
||||
json.append(",");
|
||||
}
|
||||
}
|
||||
json.append("}");
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
private String getString(Video video, Field declaredField) throws IllegalAccessException {
|
||||
declaredField.setAccessible(true);
|
||||
Object value = declaredField.get(video);
|
||||
if (declaredField.get(video) instanceof Integer) {
|
||||
return "\"" + declaredField.getName() + "\"" + ": " + value;
|
||||
}
|
||||
return "\"" + declaredField.getName() + "\"" + ": " + "\"" + value.toString() + "\"";
|
||||
}
|
||||
}
|
||||
|
@@ -59,7 +59,7 @@ public class Video {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{"
|
||||
+ "\"id\": \"" + id + "\","
|
||||
+ "\"id\": " + id + ","
|
||||
+ "\"title\": \"" + title + "\","
|
||||
+ "\"length\": " + length + ","
|
||||
+ "\"description\": \"" + description + "\","
|
||||
|
@@ -48,7 +48,7 @@ public class VideoResource {
|
||||
* @param fields fields to get information about
|
||||
* @return json of specified fields of particular video by id
|
||||
*/
|
||||
public String getDetails(Integer id, String... fields) {
|
||||
public String getDetails(Integer id, String... fields) throws Exception {
|
||||
if (fields.length == 0) {
|
||||
return videos.get(id).toString();
|
||||
}
|
||||
|
Reference in New Issue
Block a user