I am making one webservice application in this I am getting json response and I am parsing that json and I am showing that result in listview.Right now I want to parse with jackson library.I tried some far but I am not getting anything.
code:
private static class Holder
{
ArrayList<UpcomingPojo> holderlist;
}
ObjectMapper objmapper=new ObjectMapper();
Holder holderPojo =objmapper.readValue(jsonResponse,Holder.class);
UpcomingPojo contact = holderPojo.holderlist.get(0);
String name=contact.getName();
pojo:
#JsonIgnoreProperties(ignoreUnknown=true)
public class UpcomingPojo {
String no,name,desc;
public String getNo() {
return no;
}
public String getName() {
return name;
}
}
json:
[
{
"no":"12000",
"name":"ram"
},
{
"no":"12532",
"name":"ravi"
}
]
This is the code for parsing JSON using jackson library.
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient
.execute(new HttpGet(url));
InputStream is = response.getEntity().getContent();
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createJsonParser(is);
JsonToken token = jsonParser.nextToken();
if (token == JsonToken.START_ARRAY) {
while (token != JsonToken.END_ARRAY) {
token = jsonParser.nextToken();
if (token == JsonToken.START_OBJECT) {
while (token != JsonToken.END_OBJECT) {
token = jsonParser.nextToken();
if (token == JsonToken.FIELD_NAME) {
String objectName = jsonParser
.getCurrentName();
jsonParser.nextToken();
if (0 == objectName
.compareToIgnoreCase("no")) {
Log.d("","no="+jsonParser.getText());
} else if (0 == objectName
.compareToIgnoreCase("name")) {
Log.d("","name="+jsonParser.getText());
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "exception2");
}
Related
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
I am getting json response string like this.
[
"assets\/imgs\/choicelogos\/choice-logo.jpg",
"assets\/imgs\/choicelogos\/family-health-logo.jpg",
"assets\/imgs\/choicelogos\/four-corners-logo.jpg",
"assets\/imgs\/choicelogos\/grady-logo.jpg",
"assets\/imgs\/choicelogos\/hands-logo.jpg",
"assets\/imgs\/choicelogos\/morehouse-logo.jpg",
"assets\/imgs\/choicelogos\/smc-logo.jpg"
]
And this is my approach to parse this string using ObjectMapper class.
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<WebAPIResponse> someClassList = objectMapper.readValue(strResponseString, typeFactory.constructCollectionType(List.class, WebAPIResponse.class));
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
But I am not able to parse. It is throwing errorMsg = null. Please any one help what I need to change?
Here is the solution of this question.
#JsonIgnoreProperties(ignoreUnknown = true)
private List<String> mWebAPIResponse;
#Override
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
List<String> webAPIResponse = objectMapper.readValue(strResponseString, new TypeReference<ArrayList<String>>() {});
this.mWebAPIResponse = webAPIResponse;
} catch (Exception e) {
e.printStackTrace();
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
i'm having an issue converting Json to List<>, I have tried different solutions but no clue
My json result looks like :
{
"Return":0,
"List":[
{
"Code":524288,
"Label":"TEST"
},
{
"Code":524289,
"Label":"TEST1"
},
{
"Code":524290,
"Label":"TEST2"
}
]
}
My code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Questionaire> qstlist = new ArrayList<Questionaire>();
try {
result = new RequestTask().execute("http:/dd.com/categories/current?owner=ccc").get();
json = new JSONObject(result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstlist = (List<Questionaire>) gson.fromJson(result, listType);
Questionaire qst = null;
qst = gson.fromJson(result, Questionaire.class);
Toast.makeText(MainActivity.this, "Result "+qstlist.size(), Toast.LENGTH_SHORT).show();
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
My questionnaire class :
public class Questionaire {
String Code;
String Label;
public String getCode() {
return Code;
}
public void setCode(String Code) {
this.Code = Code;
}
public String getLabel() {
return Label;
}
public void setLabel(String Label) {
this.Label = Label;
}
}
Here is everything I can't see what's wrong about that
In this JSON, you get a list of {Code, Label} objects, but in the List property of an object.
You first need to encapsulate this list in an other object.
As in:
public class QuestionaireList {
public List<Questionaire> List;
}
List<Questionaire> qsts = gson.fromJson(result, QuestionaireList.class).List;
You need another class that maps the full result
public class MyJson {
#SerializedName("List")
private List<Questionaire> list;
#SerializedName("Return")
private Integer return1;
//... getters and setters
}
Your type then needs to bind to "MyJson" or whatever you name the class.
I'm assuming it's the List part you want to map to 'qstList'. If so then you need to extract it from the rest of the json first:
Gson gson = new Gson();
JsonObject resultObj = gson.fromJson(result, JsonObject.class);
JsonArray jsonList = resultObj.get("List").getAsJsonArray();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstList = gson.fromJson(jsonList, listType);
When I try to use my restTemplate.postForEntity I get a 404 bad request
What is my fault?
Code:
Servercaller:
public ServerError login(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
String URL = "http://"+ipAddress+"/ProjectTeamF-1.0/service/login.json";
Object[] params = new Object[]{URL,user};
new login().execute(params);
} catch (ResourceAccessException rae) {
receivedUser = null;
return ServerError.ServerNotFound;
} catch (HttpServerErrorException hsee) {
receivedUser = null;
return ServerError.WrongData;
} catch(RestClientException rce){
receivedUser = null;
return ServerError.WrongData;
} catch (Exception e) {
System.out.println("error " + e);
receivedUser = null;
return ServerError.OtherError;
}
return ServerError.NoError;
}
AsyncTask:
public class login extends AsyncTask<Object[], Void, Void> {
public ServerCaller sc = ServerCaller.getInstance();
public User body;
#Override
protected Void doInBackground(Object[]... params) {
String message = "";
try {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> _entity = new HttpEntity<User>((User)params[0][1], requestHeaders);
RestTemplate templ = new RestTemplate();
templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
ResponseEntity<User> _response = templ.postForEntity(params[0][0].toString(), _entity, User.class); //null here in order there wasn't http converter errors because response type String and [text/html] for JSON are not compatible;
body = _response.getBody();
return null;
} catch (Exception e) {
message = e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
sc.setReceivedUser(body);
}
}
When I debug the program crashes at templ.postForEntity(). The error tells me that this is a 400 - bad request.
Thanks!
i m getting this response in a result of GET request to server
{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}
i just want to extract the value of "value" from the above json response.
I m using this code to get this response
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.14.247/jdev/sys/getkey"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Parse Exception", e + "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("IO Exception 2", e + "");
}
Log.i("responseText", responseText);
Toast.makeText(MainActivity.this, responseText + "",
Toast.LENGTH_SHORT).show();
}
});
my question is that how can i parse this and get the value of only "value" tag.
thanks
you can parse current json String to get value from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
try this
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);
String value = json.getJSONObject("LL").getString("value");
Try this:
JSONObject json= json1.getJSONObject("LL");
String value= json.getString("value");
Try this,
JSONObject ResponseObject = new JSONObject(Response);
String str = ResponseObject.getJSONObject("LL").getString(value);
You can parse your response and get value try this:
try {
JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
} catch (Exception e) {
e.printStackTrace();
}
Simple and Efficient solution : Use Googlle's Gson library
Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);
or you can use this below class :
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Thank me later :)