I want to parse a JSON response using volley, JSON response contain Hindi data also, so how can I get that Hindi data in my test view
I had just parse JSON array using JSONObject and JSONArray and just fetch data by using getString() method.
final String URL = "http://[DomainName]/getSubCategory";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.cancel();
Log.d("1234","responce array "+response.toString());
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("sub_cat_list");
Log.d("1324","responce array "+array.toString());
for (int i = 0; i < array.length(); i++) {
JSONObject main_recipes = array.getJSONObject(i);
SubCatPojo pojo = new SubCatPojo();
pojo.setCatId(main_recipes.getString("id"));
pojo.setCatName(main_recipes.getString("name"));
pojo.setCatImage(main_recipes.getString("image"));
arrayList.add(pojo);
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.cancel();
Toast.makeText(Listing.this, "error in network", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("p_id", catId);
return map;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
But in logcat, I got this response
{ "sub_cat_list":[{"id":6,"name":"\u0936\u094d\u0930\u0940 \u0917\u0923\u0947\u0936 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/shree-ganesh-ji.png"},{"id":7,"name":"\u0913\u092e \u091c\u092f \u091c\u0917\u0926\u0940\u0936 \u0939\u0930\u0947 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/vishnu-ji.png"},{"id":8,"name":"\u0926\u0941\u0930\u094d\u0917\u093e \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/durga_ma.png"},{"id":9,"name":"\u0906\u0930\u0924\u0940 \u0936\u094d\u0930\u0940 \u0932\u0915\u094d\u0937\u094d\u092e\u0940 \u092e\u093e\u0924\u093e ","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/laxmi_ma.png"},{"id":10,"name":"\u0936\u093f\u0935 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/shiv.png"},{"id":11,"name":"\u0936\u094d\u0930\u0940 \u0939\u0928\u0941\u092e\u093e\u0928 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/hanuman_ji.png"},{"id":12,"name":"\u0936\u094d\u0930\u0940 \u0938\u0930\u0938\u094d\u0935\u0924\u0940 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/banner_img\/sarswati_maa.png"},{"id":13,"name":"\u0915\u0941\u0902\u091c \u092c\u093f\u0939\u093e\u0930\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/\/banner_img\/Kunj_Bihari.png"},{"id":14,"name":"\u0936\u094d\u0930\u0940 \u0936\u0928\u093f \u0926\u0947\u0935 \u0915\u0940 \u0906\u0930\u0924\u0940","img_url":"http:\/\/poojavidhi.webepower.biz\/banner_img\/shani_dev.png"}]}
Use HTML.fromHtml() :
import android.text.Html;
String base = "\u0936\u094d\u0930\u0940 \u0917\u0923\u0947\u0936 \u0906\u0930\u0924\u0940";
String decoded = Html.fromHtml(base,Html.FROM_HTML_MODE_COMPACT).toString();
Decoded: श्री गणेश आरती
Now, I didn't really dig further with the flags you can use but this one seems to work. If you stumble upon issues, you should definitely try other flags.
Using core java, Only you have to convert the unicode characters to UTF-8.
First, get the value for key 'name' while iterating over the object and then try to apply below code, and the again set the value corresponding to the key 'name'.
I'm just showing the way to convert, a part of your sample string.
String string ="\u0913\u092e \u091c\u092f \u091c\u0917\u0926\u0940\u0936 \u0939\u0930\u0947 \u0906\u0930\u0924\u0940";
byte[] utf8 = string.getBytes("UTF-8");
string = new String(utf8, "UTF-8");
System.out.println(string);
It will give you output like : 'ओम जय जगदीश हरे आरती' |
Related
I have a pretty specific problem I guess. I'm using Volley library to get a String response from URL, the response is following:
{"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0}
I get this response by converting my SQL query array to JSON in PHP
$output=$db->query("SELECT email, phone, family_name, name, role FROM users WHERE email=?", "$email")->fetchArray();
$json=json_encode($output, JSON_UNESCAPED_UNICODE);
echo"$json";
What I need to do next is go throught this JSON and insert records to local database in my Android APP. In order to do that, I do following:
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONArray jsonArr = new JSONArray(response);
for(int i=0; i < jsonArr.length();i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I keep getting the following error:
13:24:59.518 22389-22389/com.local.school I/JSONerror: org.json.JSONException: Value {"email":"imribar#gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0} of type org.json.JSONObject cannot be converted to JSONArray
Any idea what I can do on PHP side to change the JSONString (add [], or add a name to an array), or what do I need to do in Android?
Your response does not have a json array, only an object.
Array is something like this.
[{
"email": "imribar1#gmail.com",
"phone": "7(707)990-77-72",
"family_name": "Жилин2",
"name": "Иван2",
"role": 2
},
{
"email": "imribar#gmail.com",
"phone": "7(707)990-77-71",
"family_name": "Жилин",
"name": "Иван",
"role": 0
}
]
So remove the loop and try.
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
I suggest you use a JsonObjectRequest instead of StringRequest when you call Volley in your app. It is almost the same as StringRequest but it gets a JSONObject as an answer.
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// your cose goes here:
JSONObject jsonObject = new JSONObject(response.toString());
User user = new User();
user.email= jsonObject.getString("email");
user.phone=jsonObject.getString("phone");
user.firstName=jsonObject.getString("name");
user.lastName=jsonObject.getString("family_name");
user.role=jsonObject.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
jsonObjectRequest
Your json string has a json object as root object, while in code you are using JSONArray jsonArr = new JSONArray(response); to parse it as if it were an array. Assuming your used json library, you would have to start parsing the json using:
JSONObject jsonObj = new JSONObject(response);
The alternative would be to actually generate a json array ([...]) rather than a json object ({...}) so that your parsing code will recognise it. The choice you want to make will depend on whether you always send a single json object or whether you want to be able to send multiple json objects (in a json array).
I have created this app that pulls data from an API and shows it in a list. the problem I am having is that I can't pull the JSON data from an API with a nested JSON array.
In this image it is simple since all the info is in one array / table.
https://imgur.com/a/v9gsbop
but in this image, it is more difficult for me. for example, how do i call the paragraph value: line in body?
https://imgur.com/Qj5CRn8
This is the code that i am currently using to pull data from API.
private void parseJSON () {
String url = "https://blah,com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray =response.getJSONArray("items");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject article = jsonArray.getJSONObject(i);
String authorName = article.getString("article_author");
String imageUrl = article.getString("src");
String published = article.getString("first_published_at");
String description = article.getString("value");
String headline = article.getString("title");
Try this way to work with nested json array,
Try this to get the result,
Your question is not quiet clear, but what from what I understand I do think you need this solutions:
Solution: Sending Parameters along with the Request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
textView.setText("Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("parameter1 name","parameter1 Value");
params.put("parameter2 name","parameter2 Value");
return params;
};
As in the above example I have shown a get request; So suppose the URL is: "https://www.youtube.com/channel/UCXEIUll8VvOqRN-OSZ5_aOg" and parameter is "view_as" and parameter value is "subscriber" then params.put("view_as","subscriber");
Solution: If you want to pass multiple parameters to your request then,
Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() { ... }
Solution: If you want to pull the items array and get its subsequent object contents, try using an iterator instead of a for loop,
JSONArray jsonArray = (JSONArray) apiResult[0].get("body");
Iterator jsonArrayIterator = jsonArray.iterator();
while(jsonArrayIterator.hasNext()) {
JSONObject jsonObject = (JSONObject) jsonArrayIterator.next();
JSONObject jsonValue = (JSONObject) jsonObject.get("value");
JSONObject jsonOriginal = (JSONObject) jsonValue.get("original");
JSONObject jsonWidth = (JSONObject) jsonOriginal.get("width");
}
While I am hitting API using JSON I am getting the following error I don't know where is my error can anybody help in resolving it as I don't have much knowledge of Json Parsing
public void onPaymentSuccess(String s, PaymentData data) {
String paymentId = data.getPaymentId();
String signature = data.getSignature();
String orderId = data.getOrderId();
callvolly(paymentId,signature,orderId );
}
private void callvolly(final String paymentId,final String signature,final String orderId) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://staging.s.com//payment/validate" ;
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("paymentId", paymentId);
MyData.put("signature", signature);
MyData.put("orderId", orderId);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
java.lang.IllegalArgumentException: Request#getParams() or
Request#getPostParams() returned a map containing a null key or value:
(signature, null). All keys and values must be non-null.
at com.android.volley.Request.encodeParameters(Request.java:478)
at com.android.volley.Request.getBody(Request.java:466)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:275)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:249)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:94)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:123)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)
I'm trying to send a photo taken with my phone/emulator camera to a Node.js server, so I'm encoding it to make a string POST request.
I tried to encode it using other answers on the internet, with a byte array stream and a compressed version of the Bitmap. On Node.js I'm trying to decode it with a function that surely works; the problem is the encoding sent to Node.js from Java is bad.
Here is the encoding of the Bitmap:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
final String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
And my POST request for the string looks like that (I'm using Volley for server interactions):
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("RESPONSE", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", "ERROR" + error);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("image", imageEncoded);
return params;
}
};
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(postRequest);
I'm pretty sure the problem is that my encoding gets some extra % characters when sent to the server, so it can't be decoded well. I thought that in my Node.js code I had to use chunks to make a full string, like this:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
body = body.split('=');
// More code here
}
My body would look like
"image=iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz%2FH..."
so I had to use split to get only the encoding, but still it didn't work. Is there a way to transform this string in another that is not URL encoded like that? Or to get through the POST request without being modified like that?
It looks like you are using the Volley library. If so, you should consider using the JSONObjectRequest instead of the StringRequest. It would look something like this, after you got your image into a JSON String format:
String myImage = "{image:" + imageEncoded + "}"
JSONObject obj = null;
try {
obj = new JSONObject(myImage);
} catch (JSONException e1) {
e1.printStackTrace();
}
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST,url,obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
)} {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json; charset=utf-8");
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
I am not familiar with JSON so if I am using wrong terms, sorry for that.
So I have this URL:
final String PRICE_TRY_URL = "https://api.coindesk.com/v1/bpi/currentprice/try.json";
And it returns something like this:
Formatted JSON Data
{
"time":{ },
"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi":{
"USD":{
"code":"USD",
"rate":"6,911.7500",
"description":"United States Dollar",
"rate_float":6911.75
},
"TRY":{
"code":"TRY",
"rate":"35,738.0058",
"description":"Turkish Lira",
"rate_float":35738.0058
}
}
}
All I want to do is reach TRY's rate.
I get that data with the code below.
public void doNetworking(){
AsyncHttpClient client=new AsyncHttpClient();
client.get(PRICE_TRY_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("BitcoinTracker","Succes in doNetworking");
// byte[] responseBody can be parsed to a json object.
parseJson(responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("BitcoinTracker", "Fail " + error.toString());
}
}
);
And here is my method :
public void parseJson(byte[] responseBody){
try {
JSONObject bitcoinJson =new JSONObject(new String(responseBody));
String currency= bitcoinJson.getString("bpi");
Log.d("bitcoinmanager",currency);
} catch (JSONException e) {
Log.d("BitcoinPrice","BitcoinPriceManager onSucces converting json from byte[] failed.");
e.printStackTrace();
}
}
As you can see above I use this statement :
String currency= bitcoinJson.getString("bpi");
And with this statement, I can't reach my destination point which is TRY's rate. How can I navigate in JSON formatted text?
NOTE: I add the getting JSON data part to make sure that my question is clear, hope it is not too much.
If you're using Android, no need to use anything external:
JSONObject bitcoinJson = new JSONObject(responseBody);
JSONObject bpi = bitcoinJson.getJSONObject("bpi");
JSONObject tr = bpi.getJSONObject("TRY");
String rate = tr.getString("rate");
Original answer using the org.json.simple library, before question was tagged as Android:
JSONObject bitcoinJson = (JSONObject)new JSONParser().parse(new String(responseBody));
JSONObject bpi = (JSONObject)bitcoinJson.get("bpi");
JSONObject tr = (JSONObject)bpi.get("TRY");
String rate = (String)tr.get("rate");
Note that instead of constructing a string to pass to the JSONParser, it's a bit more efficient just to give it access to the Reader directly.
You can use this code with Gson library:
client.get(PRICE_TRY_URL, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
// called when response HTTP status is "200 OK"
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(responseBodyString);
JsonObject bpi = jsonObject.get("bpi").getAsJsonObject();
JsonObject tryObject = bpi.get("TRY").getAsJsonObject();
String rate = tryObject.get("rate").getAsString();
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
}
);
There are examples here https://github.com/codepath/android_guides/wiki/Using-Android-Async-Http-Client