java - 如何将java列表对象的特定字段转换为jsonarray

标签 java json

我有一个类(class):人

class Person{
    String name;
    String age;
}

我想将 Person 列表转换为 jsonArray,但只转换结果中的 name 字段。但是,如果我使用

List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Jack","12"));
JSONArray result = JSONArray.fromObject(persons);

结果将包括年龄字段。

我能做什么?

最佳答案

我的解决方案是util函数createJsonObjects,使用:

JSONArray result = createJsonObjects(persons, "name", "name")

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

public static JSONArray createJsonObjects( List< ? > objs, String propertyNames, String jsonKeys )
{
    Assert.hasText( propertyNames );
    Assert.notNull( objs );

    JSONArray result = new JSONArray();
    String[] propertyNameArray = propertyNames.split( ";" );
    String[] jsonKeysArray = propertyNameArray;
    if ( StringUtils.hasText( jsonKeys ) )
    {
        jsonKeysArray = jsonKeys.split( ";" );
    }

    Assert.isTrue( jsonKeysArray.length == propertyNameArray.length );
    try
    {
        Method[] methods = new Method[ propertyNameArray.length ];
        for ( Object obj : objs )
        {
            for ( int i = 0; i < propertyNameArray.length; i++ )
            {
                methods[ i ] = BeanUtils.getPropertyDescriptor( obj.getClass(),
                                                                propertyNameArray[ i ] ).getReadMethod();
            }
            JSONObject json = new JSONObject();
            for ( int i = 0; i < propertyNameArray.length; i++ )
            {
                if ( obj != null )
                    json.element( jsonKeysArray[ i ],
                                  ReflectionUtils.invokeMethod( methods[ i ], obj ) );
            }
            result.add( json );
        }

    }
    catch ( Exception e )
    {
        throw new RuntimeException( e );
    }

    return result;
}

关于java - 如何将java列表对象的特定字段转换为jsonarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8892525/

相关文章:

java - 如何使用 URL 的搜索引擎返回搜索结果?

Java从另一个 Controller 设置文本,但UI不刷新

javascript - 我正在尝试从 JSON 文件检索数据,但在从特定属性检索信息时遇到问题

c# - 有什么方法可以更改 JSON 中的日期时间格式吗?

java - Google服务帐户授权错误

java - 在javascript中从mysql获取列表变量

java - 序列化已经有 POJO 的 id (java.lang.String)

javascript - 使用类和接口(interface)有什么区别?

java - 学习java...到底为什么这个图像会闪烁?

ios - 使用 Codable 解码具有相似键的嵌套 JSON