Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/main/java/com/innohotsource/hotjson/Json/ObjectToJson.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.innohotsource.hotjson.Json;

import org.json.simple.*;

import java.lang.reflect.Field;

public class ObjectToJson {

public static JSONObject toJson(Object obj) throws IllegalAccessException {
JSONObject jsonObject = new JSONObject();
return toJson(obj, jsonObject);
}

private static JSONObject toJson(Object obj, JSONObject map) throws IllegalAccessException {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String key = field.getName();
// Object 인 경우 || String, Wrapper Type 인 경우 || Array 인 경우??? 여튼 조건이 필요하다
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

추가 구현 부분 확인했습니다!

Object value = field.get(obj);

if(value instanceof String){
map.put(key, value.toString());
continue;
}

if(value instanceof Double){
if(((Double)value).isInfinite() || ((Double)value).isNaN())
map.put(key, "null");
else
map.put(key, value);
continue;
}

if(value instanceof Float){
if(((Float)value).isInfinite() || ((Float)value).isNaN())
map.put(key, "null");
else
map.put(key, value);
continue;
}

if(value instanceof Number){
map.put(key, value);
continue;
}

if(value instanceof Boolean){
map.put(key, value);
continue;
}
Comment on lines +23 to +52
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

primitive 타입을 찾는 로직을 확인했습니다.
내부적으로 논의한 JSON의 값이 숫자일때 명확히 어떻게 동작하는지만 확인하면 될것 같습니다.


// Arr 혹은 List 인지 확인하고 처리하는 로직? 아마도 필요할 것 같음...

if(value instanceof Object){
JSONObject newMap = toJson(value);
map.put(key, newMap);
}
Comment on lines +56 to +59
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSON의 value의 object가 다양한 wrapper를 포함할때 로직을 어떻게 구현해야할지는
다같이 좀 더 고민해봐야할것 같습니다.


}

return map;
}

}