#631 - Partial Response : Implement Field to json conversion

This commit is contained in:
Gopinath Langote
2017-09-14 22:34:02 +05:30
parent c5b9c63b39
commit 44e4b3c803
5 changed files with 82 additions and 9 deletions

View File

@ -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() + "\"";
}
}