json数据转换成object对象及获取对象中list对象的值——完整例子,解决了MorphDynaBean 对象转换具体的实体POJO对象问题

json数据转换成object对象及获取对象中list对象的值完整例子(包含所引入的包)。

pom.xml(所需的包依赖)


        
            net.sf.json-lib
            json-lib
            2.4
            
            jdk15
        
        
        
            commons-beanutils
            commons-beanutils
            1.8.0
        

        
            commons-logging
            commons-logging
            1.1.1
        

        
            commons-collections
            commons-collections
            3.2.1
        

        
            commons-lang
            commons-lang
            2.5
        

        
            net.sf.ezmorph
            ezmorph
            1.0.6
        

用于测试的类

import com.xh.xiaoyiduo.utils.baidu.entity.CustomBean;
import com.xh.xiaoyiduo.utils.baidu.entity.Results;

import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

 public static void main(String[] args) {
        String results = "{\"log_id\":5132558772297159724,\"results\":[{\"name\":\"[default]\",\"score\":0.9850209951400757},{\"name\":\"vacuum\",\"score\":0.014979000203311443}]}";

        JSONObject jsonObject = JSONObject.fromObject(results);
        Map classMap = new HashMap<>();
        classMap.put("results", Results.class);
        CustomBean customBean = (CustomBean) JSONObject.toBean(jsonObject, CustomBean.class, classMap);

        List rsList = customBean.getResults();
        System.out.println(rsList);
        for(Results rs : rsList){
            if(rs.getName().equals("vacuum")){
                System.out.println(rs.getScore() + " " + rs.getName());
            }
        }
        
 }

CustomBean 类

import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定制Bean
 */
@Component
public class CustomBean {
    private Long log_id;
    private List results;

    public Long getLog_id() {
        return log_id;
    }

    public void setLog_id(Long log_id) {
        this.log_id = log_id;
    }

    public List getResults() {
        return results;
    }

    public void setResults(List results) {
        this.results = results;
    }
}

Results 类

package com.xh.xiaoyiduo.utils.baidu.entity;

import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 结果bean
 */
@Component
public class Results {
    private String name;
    //如果出现解析错误,可以考虑换成Object类型哦
    private BigDecimal score;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getScore() {
        return score;
    }

    public void setScore(BigDecimal score) {
        this.score = score;
    }
}

运行测试类,结果输出:
在这里插入图片描述

你可能感兴趣的:(Java)