Reputation: 23
I am getting error while doing deserialization.
I have an URL and I am getting JSON data from that URL, by using the code below in sb
variable but how can I deserialize it by using this code?
My JSON data is:
{ "status": "success",
"msg": [
{ "fav_food": "roti",
"user_name": "123",
"email": "[email protected]" },
{ "fav_food": "iii",
"user_name": "343",
"email": "[email protected]" },
{ "fav_food": "paneer",
"user_name": "343",
"email": "[email protected]"}
]
}
Code:
package com.pack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@SuppressWarnings("serial")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Collection_to_jacksonJsonServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException {
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
Map<String,Directory> contacts=new HashMap<String,Directory>();
ObjectMapper ob=new ObjectMapper();
List<Data> l=new ArrayList<Data>();
URL url=new URL("https://api-demo-py.appspot.com/getAllUsers");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
StringBuilder sb=new StringBuilder();
BufferedReader br=new BufferedReader(new
InputStreamReader(request.getInputStream()));
String line;
try
{
//read from the urlConnection via the bufferedReader
while ((line = br.readLine()) != null)
{
sb.append(line);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(sb);
String jsonString=sb.toString();
l= ob.readValue(jsonString,new TypeReference<List<Data>>(){});
}
}
Upvotes: 1
Views: 4056
Reputation: 4624
well you have to deserialize to object of following:
class Wrapper {
public String status;
public List<Data> msg;
}
Upvotes: 1