且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java泛型:将嵌套的json响应映射到Java对象

更新时间:2023-01-16 19:58:26

…我遵循了[@davidxx的]解决方案,但是当返回类型应该是列表或数组时,它似乎不起作用.我将如何处理这种情况?……"

通过一个过程,我将其称为" EDD "(" 实验驱动开发 ),以下处理这些情况的方法应运而生了……

Through a process I call „EDD" („Experiment-driven Development") the following way to handle those cases emerged…

public static < T > T unbox( Map< String, T > data, String key, Class< ? > ofType ) {
    if ( data != null && data.containsKey( key ) ) {
        return (T)ofType.cast( data.get( key ) ) ;
    }
    return null;
}

您可以在 main(String []) 中进行观察> 以下调用成功返回了预期结果…

You can observe in main(String[]) that the following calls successfully return the expected result…

...
List< String > unBoxedList = unbox( mapOfLists, foo, List.class );
...
List< ? >[ ] unBoxedArrayOfLists = unbox( mapOfArrayOfLists, "bar", List[ ].class );
... 
String unBoxedString = unbox( mapOfStrings, foo, String.class );
...
Integer unBoxedInteger = unbox( mapOfIntegers, bar, Integer.class );
...

点击上方链接中页面顶部绿色的 开始 按钮,以运行实验.

Click the green Start button at the top of the page in the link above, to run the experiment.

在@ saran3h的注释澄清了他的用例之后,反馈从 a实验的后续迭代

After feedback in the comments from @saran3h that clarified his use case, the following refactor emerged from a subsequent iteration of the experiment

public class BaseUtil {
    
    public List<Object> associatedPartyRole ;
    
    // TODO: Make this method generic
    public static < T > T unbox( Map< String, T > data, String key, Class< ? > ofType ) {
        if ( data != null && data.containsKey( key ) ) {
            return (T)ofType.cast( data.get( key ) ) ;
        }
        return null;
    }
    
    public void unboxAssociatedPartyRole(Map<String, Object> data) {
        this.associatedPartyRole = (List)unbox(data, "foo", Object.class);        
    }
}

该新案件已成功通过……测试

That new case was successfully tested with…

...
private static final Map<String, Object> mapOfObjects = new HashMap< >( ); 
...
mapOfObjects.put( foo, (Object)mapOfLists.get( foo ) );
...
BaseUtil user = new BaseUtil( );

user.unboxAssociatedPartyRole( mapOfObjects );

List< Object > objs = user.associatedPartyRole;

assertIsA( objs, List.class );

使用上述重构(法语> )观察运行实验的结果...

Observe the results of running the experiment with the above refactor (pardon my French)…

[What The Reifiable Fuck@&*%$*!?]
                     EXPERIMENT SUCCESSFUL