First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}
Related
I have login system, and i get NullPointerException after getting response or in process request generation. My login request is:
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(res == "sucess"){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent upanel = new Intent(getApplicationContext(), Main.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username/password");
}
}
}
And login building is:
public JSONArray loginUser(String email, String password, String appkey) {
String conc = email + password + appkey;
JSONArray json = jsonParser.getJSONFromUrl(loginURL + "?login=" + email
+ "&password=" + password + "&sign=" + conc);
return json;
}
In the jsonParser i have this code:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
// try parse the string to a JSON object
jObj = new JSONArray(json);
// return JSON String
return jObj;
}
}
By the way JSON response of the type:
{ "status": "success",
"message": "",
"session_id": "asdasddfcvxgdgfdfv",
"user":
[{ "company": "company",
"last_name": "last_nameĀ·",
"name": "name",
"middle_name": "middle_name",
"phone": "+1234567890",
"photo": "avatar.png" }] }
After this action i get error of "null values" like this:
Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0 of
Try this way,hope this will help you to solve your problem.
public JSONObject getJSONFromUrl(String url) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpEntity.getContent(), HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
reader.close();
}
jObj = new JSONObject(reader.toString());
return jObj;
} catch (MalformedURLException localMalformedURLException) {
return null;
} catch (IOException localIOException) {
return null;
}catch (Exception e){
return null;
}
}
Your response is a JsonObject and you are parsing it to JSONArray
For more info. http://json.org/
I'm trying to receive a JSON format file throw HTTP in Android. But while i do that i guess the file comes bad formatted. The code is the following:
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI website = new URI(params[0]);
HttpGet request = new HttpGet();
request.setHeader("Content-type", "application/json");
request.setURI(website);
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
}
catch(Exception e){
Log.e("http", e.toString());
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
txt.setText((String) jObject.get("shortName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//txt.setText(result);
}
The JSON file is like this:
{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}},
...
...
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}}
This is just a part of the file.
Am I doing something wrong? I included the header in order to receive in JSON format.
Here you are.
try{
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("lectiveSemesters");
for(int i = 0; jarray != null & i < jarray.length(); i++){
JSONObject jitem = (JSONObject) jarray.get(i);
}
} catch (Exception e){
}
I am working with webservice in an android app. I could not parse the following response in app. it always gives the
org.json.JSONException: Value
[{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak#triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]
at data of type java.lang.String cannot be converted to JSONArray.
Below is my code:
StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response from webservice
{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak#triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}
try using something like:
jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response
{
"data":"[{\"METER_READING\":\"25...}]"
}
The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.
So this should work:
JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
try this simple code:
JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");
EDIT
Thanks #McDowell for observation
new JSONArray(new JSONTokener(jObject.optString("data")));
You can do this way :
JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Your json should be like this
{
"myarray": [
{
"METER_READING": "15",
"UTILITY_PLAN": "1",
"uname": "vinayak#triffort.com",
"kwh_usage": "3",
"meter_reading_date": "02-13-2014",
"ESID": "abc",
"METER_ID": "abc100"
}
]
}
for network call
public String initializeConnection(String url) {
String result = null;
JSONObject jObj;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(client==null){Log.i("Clinet **************** ", "Client is null");}
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse res = client.execute(post);
result = inputStreamToString(res.getEntity().getContent()).toString();
Log.d("Result from server:", result);
jObj = new JSONObject(result.trim());
} catch (JSONException e1) {
Log.e("Json Exception", e1.toString());
} catch (ClientProtocolException e2) {
Log.e("Client Protocol", e2.toString());
} catch (IOException e3) {
Log.e("Io exception", e3.toString());
}
return result;
}
private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
to retrive from the json
ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);
jObj = new JSONObject(result);
JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));
now the data is stored in the params you can differentiate & store it as you want
In my android app I am using JSON to get data from a wordpress website. It works good except the fact that just in titles of articles there are some weird characters. I don't know why if encoding is good with other text content why is it that if title has some non-standard character like "&" it gives some question marks etc. Here is my JSON parsing code I would be thankful if someone could take a look and answer me what is wrong with encoding here ?
private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
// parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
URL httpurl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) httpurl.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("date"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("content"));
item.setCustomFields(post.getString("custom_fields"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected Integer doInBackground(Void... params)
{
String readMyJSON = readMyJSON();
try {
JSONArray jsonArray = new JSONArray(readMyJSON);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
This is not working, during JSONArray jsonArray = new JSONArray(readMyJSON);, JSONException occurs. Could somebody tell me where is the problem? Thanks in advance.
P.S.: Method I use:
public String readMyJSON()
{
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://search.twitter.com/search.json?q=android");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
This method seems to be allright.
In short, the response from twitter is not an JSON array, so you get an exception. If you want the array of results, do the following:
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = object.getJSONArray("results");
I suggest you read the Twitter API docs. Specifically, https://dev.twitter.com/docs/api/1/get/search.
Can you try this:
JSONArray jsonArray = new JSONArray("["+readMyJSON+"]");
I hope it should work.