/** * Parse the json and returns the object itself. */ default <T> T withParsingJson(JsonValue json) { parseJson(json); return (T)this; } }
/** * Parse all the items to the given type using {@link JsonParsable#parseJson(JsonValue)}. */ public <T extends JsonParsable> List<T> parseList(Supplier<T> factory) { List<T> newList = new ArrayList<>(); for(Object item : this.list) { T obj = factory.get(); obj.parseJson(JsonValue.of(item)); newList.add(obj); } return newList; }
/** * Parse the json. */ default void parseJson(String json) { parseJson(JSON.parse(json)); }
/** * Parse all the items to the given type using {@link JsonParsable#parseJson(JsonValue)}. */ public <T extends JsonParsable> List<T> parseList(Class<T> type) { List<T> newList = new ArrayList<>(); ReflectClass rc = ReflectClass.of(type); for(Object item : this.list) { T obj = rc.newInstance(); obj.parseJson(JsonValue.of(item)); newList.add(obj); } return newList; }
try { temp = (JsonParsable) cls.newInstance(); temp.parseJson(jsonStr); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e);
@Override protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { try(InputStream is = inputMessage.getBody()) { if(clazz.isArray()) { try(InputStreamReader reader = new InputStreamReader(is, getCharset(inputMessage))) { try { JsonArray a = JSON.parse(reader).asJsonArray(); Object o = Array.newInstance(clazz.getComponentType(), a.length()); for(int i=0;i<a.length();i++) { Object item = Reflection.newInstance(clazz.getComponentType()); ((JsonParsable)item).parseJson(a.getObject(i)); Array.set(o, i, item); } return o; }catch (Exception e) { throw new HttpMessageNotReadableException(e.getMessage(), e); } } }else { Object o = Reflection.newInstance(clazz); try { ((JsonParsable)o).parseJson(IO.readString(is, getCharset(inputMessage))); return o; }catch (Exception e) { throw new HttpMessageNotReadableException(e.getMessage(), e); } } } }
@Override public Object read(Type type, Class contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { if(type instanceof Class<?>) { return readInternal((Class)type, inputMessage); }else { ParameterizedType parameterizedType = (ParameterizedType)type; Class typeArgument = (Class)parameterizedType.getActualTypeArguments()[0]; Collection c = newCollection((Class)parameterizedType.getRawType()); try(InputStream is = inputMessage.getBody()) { try(InputStreamReader reader = new InputStreamReader(is, getCharset(inputMessage))) { try { JsonArray a = JSON.parse(reader).asJsonArray(); a.forEach(item -> { if(null == item) { c.add(null); }else { Object o = Reflection.newInstance(typeArgument); ((JsonParsable)o).parseJson(item); c.add(o); } }); }catch (Exception e) { throw new HttpMessageNotReadableException(e.getMessage(), e); } } } return c; } }