JSON wrong encoding in android app - java

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();
}
}

Related

JSON.typeMismatch(JSON.java:112) with url JSON file

it my method call
if(guest){
new JsonTask().execute("URL");
}else{
new AsyncTaskGetMareker().execute();
}
This is my method:
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
JSONObject json = new JSONObject(result);
JSONObject jsonResponse = json.getJSONObject("response");
String name = jsonResponse.getString("store_name");
String lat = jsonResponse.getString("latitude");
String lang=jsonResponse.getString("longitude");
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my error
org.json.JSONException: Value [{"id":1,"store":"дом","category_id":11,"latitude":
2020-02-10 14:24:01.689 13767-13767/? W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
I found this code on this site and am trying to implement it in my project.
I make sure that when checking, either a local or external file is loaded.
What i do wrong in my code?Please help me...I don't understand English well, please understand and forgive me
The answer that helped me from: mrgrechkinn
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result !=null){
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObject= null;
try {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("store_name");
String lat = obj.getString("latitude");
String lang=obj.getString("longitude");
String desc=obj.getString("store_desc");
String oxr=obj.getString("telephone");
String sost=obj.getString("keywords");
int cat=obj.getInt("category_id");
int id=obj.getInt("id");
Log.e("100rad",""+i);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Is there a way that I can return arrays without String[] params?

public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}

How to get the value of a child node of a json array

please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !

HTTP response not giving output

I am working on an application that interacts with a room security control device.
I want to get devices information from API. I am using HttpUrlConnection and POST method. It hits the API and I get 200 OK response but I get the out
"{"json":{"control":{"cmd":"getdevice","uid":256}}} doesn't exist"
I have tried all the solutions from stackoverflow and other platforms but it's not giving the output.
Moreover I have tested this API on Postman and it's working there and giving the device information.
Here is the code:
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String username = "admin";
String password = "888888";
URL url = null;
try {
url = new URL("http://192.168.100.25/network.cgi");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("POST");
httpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setDoInput(true);
httpRequest.setDoOutput(true);
android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
httpRequest.addRequestProperty("Authorization", "Basic " + "YWRtaW46ODg4ODg4"); // This is auth bytecode
httpRequest.connect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjectControl = new JSONObject();
jsonObjectControl.put("cmd","getdevice");
jsonObjectControl.put("uid",256);
jsonObject.put("control",jsonObjectControl);
json.put("json", jsonObject);
String encodedData = URLEncoder.encode( json.toString(), "UTF-8" );
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpRequest.getOutputStream()));
writer.write(encodedData);
writer.flush();
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader
(new InputStreamReader(httpRequest.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
sb.append(line);
Log.i("Output line: ",sb.toString());
}
while(bufferedReader.readLine()!=null);
bufferedReader.close();
int responseCode = httpRequest.getResponseCode();
String resMsg = httpRequest.getResponseMessage();
String result = sb.toString();
Log.d("Output: ","--"+result);
Log.d("Response Code: "+responseCode, "!!");
Log.d("Response MSG ","--"+resMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Value of type java.lang.String cannot be converted to JSONArray ..The Error i am recieving continuously

HERE is php file result
Array[{"username":"abc","userpassword":"abc","id":"123456789"}]
Here is Code of getting response through HTTPConnection ..
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
try {
// create connection
URL wsURL=new URL(params[0]);
conn=(HttpURLConnection) wsURL.openConnection();
conn.setConnectTimeout(15000);;
conn.setReadTimeout(10000);
// get data
InputStream in = new BufferedInputStream(conn.getInputStream());
// converting InputStream into String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
String jsonResult=sb.toString();
return jsonResult;
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
And The Code Through Which i am parsing string result into jsonArray and JsonObject
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json = jArray.getJSONObject(0);
String username = json.getString("username");
} catch (Exception e) {
error2 = e.getMessage().toString();
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
dialog.dismiss();
}
There is an error that "Value of type java.lang.String cannot be converted to JSONArray"
Try this code
try {
result = result.replace("Array","");
JSONArray jArray = new JSONArray(result);
JSONObject json = jArray.getJSONObject(0);
String username = json.getString("username");
} catch (Exception e) {
error2 = e.getMessage().toString();
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
dialog.dismiss();

Categories

Resources