SoFunction
Updated on 2025-05-19

How to convert Java List to List

Convert List<JSONObject> to List<entity class>

AvailableFastjson'stoJavaObject methodDirect conversion without intermediate serialization steps.

The following are the specific implementation and precautions:

import ;
import ;
import ;

public class Converter {
    public static List<Params6000Bean> convert(List<JSONObject> jsonObjectList) {
        return ()
                .map(json -> ())
                .collect(());
    }
}

Or through traditional loops:

import ;
import ;
import ;

public class Converter {
    public static List<Params6000Bean> convert(List<JSONObject> jsonObjectList) {
        List<Params6000Bean> result = new ArrayList<>();
        for (JSONObject json : jsonObjectList) {
            Params6000Bean bean = ();
            (bean);
        }
        return result;
    }
}

Key Step Description

1) TraversalList<JSONObject>

Use the Stream API or loop to process each one by oneJSONObject

2) CalltoJavaObject()method

Fastjson's(Class<T> clazz)Map the JSON data structure directly to the target bean class.

3) Collect results

ConvertedParams6000BeanObjects collected newListmiddle.

Things to note

Field Match

  • Params6000BeanThe field name of the simultaneous field name must be the same as the key name in JSON.
  • If the field names are inconsistent, you can use it@JSONField(name = "json_key")annotation:
public class Params6000Bean {
    @JSONField(name = "user_name")
    private String userName;
    // Other fields and getter/setter}

Type Compatibility

  • The value type in JSON must be compatible with the Bean field type (e.g.StringchangeIntegerWill fail).
  • If the types are inconsistent, you need to customize the deserialization logic or use Fastjson's@JSONField(deserializeUsing = )

Null value processing

  • If a field in JSON isnull, the corresponding fields of bean must be allowednull(If using the packaging typeIntegerInsteadint)。

Performance optimization

  • Use directlytoJavaObject()Avoid serialization to strings, which is more efficient.
  • For large data volumes, it is recommended to use Stream API or parallel streams (thread safety is required).

Example Bean class

public class Params6000Bean {
    private String name;
    private int age;
    private boolean isStudent;
    // There must be a getter/setter or public field}

Exception handling

If there may be missing fields or type errors in JSON data, it is recommended to catch exceptions:

try {
    List&lt;Params6000Bean&gt; beans = convert(jsonObjectList);
} catch (Exception e) {
    // Handle conversion exceptions (such as missing fields, mismatched types)    ();
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.