美文网首页Java
java.lang.ClassCastException/ ja

java.lang.ClassCastException/ ja

作者: 一亩三分甜 | 来源:发表于2020-04-18 16:46 被阅读0次

Java中转JSONObject报错

java.lang.ClassCastException: java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject

意思是不能将字符串转为JSONObject,有两个类,一个父类BaseLivenessResult有一个属性为JSONObject类型的jsonResult,一个子类BaseLivenessV3Result继承于BaseLivenessResult。

 @Test
    public void testField() throws Exception{
        String jsonString = "{\n" +
                "            \"time_used\":1448,\n" +
                "                \"verification\":{\n" +
                "            \"idcard\":{\n" +
                "                \"confidence\":86.63057,\n" +
                "                        \"thresholds\":{\n" +
                "                    \"1e-3\":62.168713,\n" +
                "                            \"1e-5\":74.39926,\n" +
                "                            \"1e-4\":69.31534,\n" +
                "                            \"1e-6\":78.038055\n" +
                "                }\n" +
                "            }\n" +
                "        },\n" +
                "            \"biz_no\":\"\",\n" +
                "                \"result_message\":\"SUCCESS\",\n" +
                "                \"result_code\":1000\n" +
                "        }";
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonString);

        JSONObject jo = null;

        BaseLivenessResult baseLivenessResult = new BaseLivenessResult();

        baseLivenessResult.setJsonResult(jsonObject);

        jo = (JSONObject)getValueByKey(baseLivenessResult,"jsonResult");

        System.out.println("-------BaseLivenessResult------"+jo);

        BaseLivenessV3Result baseLivenessV3Result = new BaseLivenessV3Result();

        baseLivenessV3Result.setJsonResult(jsonObject);

        jo = (JSONObject)getValueByKey(baseLivenessV3Result,"jsonResult");

        System.out.println("-------BaseLivenessV3Result-------"+jo);

    }
    
        public Object getValueByKey(Object obj, String key) throws Exception {
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            System.out.println("-----f-----"+f);
            f.setAccessible(true); // 设置些属性是可以访问的
            try {

                if (f.getName().endsWith(key)) {
                    return f.get(obj);
                }
            } catch (Exception e) {
                throw e;
            }
        }
        // 没有查到时返回空字符串
        return "";
    }
    
//输出
-----f-----private java.lang.String com.cloud.spring.base.BaseLivenessResult.requestId
-----f-----private com.alibaba.fastjson.JSONObject com.cloud.spring.base.BaseLivenessResult.jsonResult
-------BaseLivenessResult------{"result_message":"SUCCESS","biz_no":"","result_code":1000,"verification":{"idcard":{"thresholds":{"1e-6":78.038055,"1e-5":74.39926,"1e-4":69.31534,"1e-3":62.168713},"confidence":86.63057}},"time_used":1448}
-----f-----private java.lang.String com.cloud.spring.base.BaseLivenessV3Result.bizNo
-----f-----private java.lang.String com.cloud.spring.base.BaseLivenessV3Result.resultMessage

java.lang.ClassCastException: java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject

    at com.cloud.spring.base.TestField.testField(TestField.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

发现通过getDeclaredFields()方法并不能得到子类中的属性,只能得到本类中的属性,所以子类中并不能获取到jsonResult这个属性对象,返回的是“”空字符串,空字符串不能强转为JSONObject对象。
通过查看getDeclaredFields的解释得到:but excludes inherited fields,所以不能获取到子类中的属性对象。

 /**
     * Returns an array of {@code Field} objects reflecting all the fields
     * declared by the class or interface represented by this
     * {@code Class} object. This includes public, protected, default
     * (package) access, and private fields, but excludes inherited fields.
     *
     * <p> If this {@code Class} object represents a class or interface with no
     * declared fields, then this method returns an array of length 0.
     *
     * <p> If this {@code Class} object represents an array type, a primitive
     * type, or void, then this method returns an array of length 0.
     *
     * <p> The elements in the returned array are not sorted and are not in any
     * particular order.
     *
     * @return  the array of {@code Field} objects representing all the
     *          declared fields of this class

相关文章

网友评论

    本文标题:java.lang.ClassCastException/ ja

    本文链接:https://www.haomeiwen.com/subject/oslivhtx.html