11package club .someoneice .json ;
22
3- import club .someoneice .json .node .ArrayNode ;
4- import club .someoneice .json .node .JsonNode ;
5- import club .someoneice .json .node .MapNode ;
3+ import club .someoneice .json .api .JsonVar ;
4+ import club .someoneice .json .node .*;
65
76import java .io .File ;
87import java .io .InputStream ;
98import java .lang .reflect .Field ;
9+ import java .lang .reflect .Modifier ;
1010import java .util .ArrayList ;
1111import java .util .Collections ;
1212import java .util .HashMap ;
@@ -112,7 +112,7 @@ public <T> T tryPullAsClass(Class<? extends T> clazz, File file) throws Instanti
112112 return tryPullAsClass (clazz , jsonMap );
113113 }
114114
115- public <T > T tryPullAsClass (Class <? extends T > clazz , MapNode jsonMap ) throws InstantiationException , IllegalAccessException {
115+ public <T > T tryPullAsClass (Class <T > clazz , MapNode jsonMap ) throws InstantiationException , IllegalAccessException {
116116 T targetClass = clazz .newInstance ();
117117 Field [] fields = targetClass .getClass ().getDeclaredFields ();
118118
@@ -125,6 +125,36 @@ public <T> T tryPullAsClass(Class<? extends T> clazz, MapNode jsonMap) throws In
125125 return targetClass ;
126126 }
127127
128+ public <T > MapNode tryPushFromClass (T clazz ) throws IllegalAccessException {
129+ final MapNode root = new MapNode ();
130+ final Field [] fields = clazz .getClass ().getDeclaredFields ();
131+ for (Field field : fields ) {
132+ field .setAccessible (true );
133+ boolean flag = field .isAnnotationPresent (JsonVar .class );
134+ if (!flag && Modifier .isStatic (field .getModifiers ())) {
135+ continue ;
136+ }
137+
138+ final String name = flag ? field .getAnnotation (JsonVar .class ).value () : field .getName ();
139+ final Object obj = field .get (clazz );
140+ final String clazzName = obj .getClass ().getSimpleName ();
141+ final JsonNode <?> node ;
142+ if (obj instanceof String ) {
143+ node = new StringNode ((String ) obj );
144+ } else if (obj instanceof Integer ) {
145+ node = new IntegerNode ((int ) obj );
146+ } else if (obj instanceof Number ) {
147+ node = new DoubleNode ((double ) obj );
148+ } else if (obj instanceof Boolean ) {
149+ node = new BooleanNode ((boolean ) obj );
150+ } else continue ;
151+
152+ root .put (name , node );
153+ }
154+
155+ return root ;
156+ }
157+
128158 public <T > List <T > tryPullAsClassList (Class <? extends T > clazz , String str ) throws InstantiationException , IllegalAccessException {
129159 JsonNode <?> jsonNode = this .parse (str );
130160 return createClassList (clazz , jsonNode );
0 commit comments