-2

I have a link https://jsonplaceholder.typicode.com/posts which returns data in JSON format. How to convert that into Object format?

public String ExposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        String forresouseURL="https://jsonplaceholder.typicode.com/posts";
        ResponseEntity<String> response= restTemplate.getForEntity(forresouseURL, String.class);
        Gson gson = new Gson(); // Or use new GsonBuilder().create();
        String target2 = gson.toJson(response, User.class);
        HashMap<String, String> jsonObject= response;
        System.out.println(target2);
        //response.getBody().
        return target2; 
    }

This is what I have tried but its not returning any value.

I have to get JOSN value in Object format then have to insert In MySQL DB.

James Z
  • 12,209
  • 10
  • 24
  • 44

7 Answers7

2

The response from the link you have is not a User, but a List<User> - try to deserialize to that.

Your code should be similar to this (I tried to prettify this a bit):

    public List<User> exposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        ResponseEntity<String> response= restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts", String.class);
        Gson gson = new Gson();
        return gson.fromJson(response.getBody(), List.class);
    }

Also, if you don't have a specific reason to use Gson, I think you can do this:

    public List<User> exposeServices() {
        RestTemplate restTemplate= new RestTemplate();
        return restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts", List.class).getBody();
    }

As mentioned in the comments, this has a warning on a cast.

orirab
  • 2,915
  • 1
  • 24
  • 48
0

Jackson is a JSON serializer/deserializer that is included with spring by default and used by RestTemplate by default.

What the endpoint is returning is a list of Users so you can't deserialize it to a User directly, it has to be a of type List<User>.

public List<User> exposeServices() {
    RestTemplate restTemplate= new RestTemplate();
    return restTemplate.exchange("https://jsonplaceholder.typicode.com/posts", 
        HttpMethod.GET, 
        null,   
        new ParameterizedTypeReference<List<User>>() {})
        .getBody();
}

If you pass just List.class into RestTemplate it will not know what it is you want your list to contain and you probably will get a warning from the compiler.

We can bypass this by wrapping our List<User> into a ParameterizedTypeReference which is a type used for this, for adding parameters to types (list is a type, and it wants a parameter, in this case user).

You can read more about it here Sending lists with RestTemplate

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
-1

It is duplicated question: Google Gson - deserialize list<class> object? (generic type)

Your solution is using array instead of one object:

User[] users = gson.fromJson(response, User[].class);
-1

Use Jackson's FasterXML library. They have an ObjectMapper class that will let you convert from a JSON to a Java object as long as you tell it which fields are which.

Ethan Seal
  • 31
  • 8
-1

You can use the following solution for this

First, you need three libraries "Jackson-Databind", "jackson-annotations","jackson-core" which should be of the same version. Following is the sample code

String jsonString = "<The json user list you received>";
     ObjectMapper mapper = new ObjectMapper();

    List user =  mapper.readValue(jsonString.getBytes(), List.class);

    Iterator it = user.iterator();

    List<User> userList = new ArrayList<>();

    while(it.hasNext())
    {
        User receivedUser = new User();
        LinkedHashMap receivedMap = (LinkedHashMap)it.next();
        receivedUser.setUserId((Integer)receivedMap.get("userId"));
        receivedUser.setId((Integer)receivedMap.get("id"));
        receivedUser.setTitle((String)receivedMap.get("title"));
        receivedUser.setBody((String)receivedMap.get("body"));
        userList.add(receivedUser);
    }

I have already created user class. At last the userList will have all the users that came.

venkat
  • 442
  • 5
  • 17
-2

U can try this for converting JSON to Object in Java

public class JSONToJavaExample
{
   public static void main(String[] args)
   {
      Student S1= null;
      ObjectMapper mapper = new ObjectMapper();
      try
      {
         S1 =  mapper.readValue(new File("json file path"), Student.class);
      } catch (JsonGenerationException e)
      {
         e.printStackTrace();
      } catch (JsonMappingException e)
      {
         e.printStackTrace();
      } catch (IOException e)
      {
     e.printStackTrace();
      }
      System.out.println(S1);
   }
-2

You will have to download the json dependency from this link

import org.json.JSONArray;
import org.json.JSONObject;

public class ParseJSON {

    static String json = "{/Your json string/}";

    public static void main(String[] args) {
        JSONObject obj = new JSONObject(json);
    }
}
Nandakumar
  • 11
  • 1
  • 3