簡體   English   中英

如何將Java列表對象的特定字段轉換為jsonarray

[英]How to transform specific fields of java list object to jsonarray

我有一堂課:人

class Person{
    String name;
    String age;
}

我想將“人員”列表轉換為jsonArray,但結果中僅轉換名稱字段。 但是,如果我使用

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM