Home > database >  How to convert List<?> to List<Object> in java?
How to convert List<?> to List<Object> in java?

Time:10-24

How to convert List<?> to List in java?

For example I have this class

@Data
public class Example {
 private List<?> data;
}

and I used in this function

@PostMapping("/getResult")
@ResponseBody
public Result getResult(@RequestBody String json) {
     
      Gson gson = new Gson();
      Example xmpl = gson.fromJson(json, Example.class);
      List<MyObject> source = (List<MyObject>)xmpl.getData(); //==> error

      // get Result

      return result;

}

It will give this error

  class com.google.gson.internal.LinkedTreeMap cannot be cast to class com.myproject.MyObject

EDITED:

The real problem is not from converting ? to object, but from converting LinkedTreeMap to the object

WORKAROUND :

    String jsonData = gson.toJson(xmpl.getData());

    MyObjectBean[] objs = gson.fromJson(jsonData,MyObjectBean[].class);

CodePudding user response:

You could go with two solutions, to start with:

  1. You can change the Generic type, this way You don't say data is any collection, but it's a collection of type <T>. Now You can create classes with given type anywhere You need it.

Generic value <?> means in general that you don't care what is inside, and probably You won't read it anyway. When You are interested only if collection is null or what it's size.

When You need to do something with it, then use Generic types.

Example:

public class Example<T> {
 private List<T> data;
}

Now inside of your controller, create a private class, to deserialize your payload.

static class MyObjectExample extends Example<MyObject>{
}

Now you can use it do decode JSON:

  MyObjectExample xmpl = gson.fromJson(json, MyObjectExample.class);
  List<MyObject> source = xmpl.getData();

Now if your code can be serialized to MyObject it will work.

  1. Spring supports deserialization also.

If you have a @RestController annotation added to your Controller class

Example:

@PostMapping("/getResult")
public Result getResult(@RequestBody MyObjectExample xmpl) {

      // get Result
      return result;
}

Or you can add

consumes = MediaType.APPLICATION_JSON_VALUE

to your REST method.

Try using Spring to convert your value for you.

You can find more

CodePudding user response:

The real issue is not when converting ? to MyObject, but the LinkedTreeMap to MyObject, from this explanation by @harsh

so I did this workaround

String jsonData = gson.toJson(xmpl.getData());

MyObjectBean[] objs = gson.fromJson(jsonData,MyObjectBean[].class);
  • Related