#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() + "\"";
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user