001package gudusoft.gsqlparser.util.json; 002 003import gudusoft.gsqlparser.dlineage.util.BeanUtil; 004 005import java.io.IOException; 006import java.io.Writer; 007import java.lang.reflect.Array; 008import java.util.ArrayList; 009import java.util.Collection; 010import java.util.List; 011 012public class JSONRender { 013 014 public String toJSONString(Object obj) { 015 return toJSONString(obj, false); 016 } 017 018 public String toJSONString(Object obj, boolean ignoreId) { 019 if (obj.getClass().isArray()) { 020 int size = Array.getLength(obj); 021 List<Object> arrayList = new ArrayList<>(size); 022 for (int i = 0; i < size; i++) { 023 arrayList.add(Array.get(obj, i)); 024 } 025 obj = arrayList; 026 } 027 028 if (obj instanceof Collection) { 029 // The elements go in as they are: the serializer writes a bean as an object itself, and 030 // mapping a String or a number through bean2Map wrote its getters, {"bytes":...} (Mantis 4799). 031 return new JSONSerializer(ignoreId).serialize(new ArrayList<Object>((Collection<?>) obj)); 032 } else { 033 return new JSONSerializer(ignoreId).serialize(BeanUtil.bean2Map(obj)); 034 } 035 } 036 037 public void toJSONString(Object obj, Writer writer) throws IOException { 038 toJSONString(obj, false, writer); 039 } 040 041 public void toJSONString(Object obj, boolean ignoreId, Writer writer) throws IOException { 042 if (obj.getClass().isArray()) { 043 int size = Array.getLength(obj); 044 List<Object> arrayList = new ArrayList<>(size); 045 for (int i = 0; i < size; i++) { 046 arrayList.add(Array.get(obj, i)); 047 } 048 obj = arrayList; 049 } 050 051 if (obj instanceof Collection) { 052 new JSONSerializer(ignoreId).serialize(new ArrayList<Object>((Collection<?>) obj), writer); 053 } else { 054 new JSONSerializer(ignoreId).serialize(BeanUtil.bean2Map(obj), writer); 055 } 056 } 057 058 private static class Holder { 059 private static final JSONRender INSTANCE = new JSONRender(); 060 } 061 062 public static JSONRender getInstance() { 063 return Holder.INSTANCE; 064 } 065 066 private JSONRender() { 067 } 068}