Accessing data from the table - JSON/Java - java

I need to access to the "mid" but I need to sort it somehow, so I need to get the "code" and then get the "mid" value.
Can you help me with this, I have no idea how to refer to that.
Here is what I have:
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject ratesObject = jonObj.getJSONObject("rates");
String gbpcode = ratesObject.getString("code");
Double gbpRate = ratesObject.getDouble(gbpcode."mid");
Log.i("CHACHING", "GBP: " + gbpRate);
// Log.i("CHACHING", "EUR: " + eurRate);
Double usds = Double.valueOf(usdValue.getText().toString());
Double gbps = usds * gbpRate;
// Double euros = usds * eurRate;
gbpValue.setText("GBP: " + String.valueOf(gbps));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the json looks like this
http://api.nbp.pl/api/exchangerates/tables/A/?format=json

The json received is list of json objects(json array) and in each json object "rates" is another json Array.
So, in order to access mid.
public void onSuccess(String response) { Log.i("CHACHING", "HTTP Sucess");
try {
JSONArray jsonArr = new JSONArray(response);
JSONObject jsonObj=jsonArr.getJSONObject(0);
//this jsonObj holds the first jsonObject of your response
JSONArray rateList = jonObj.getJSONArray("rates");
//rateList has the list of rates you obtained
//NOW, to get all mids for this rate list
for(int i=0;i<rateList.length();i++) {
JSONObject jO=rateList.getJSONObject(i);
Double mid=jO.getDouble("mid");
Double gbpcode = jO.getString("code");
/*
your code here
*/
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Android studio JSONArray cannot be converted to JSONObject

I realise there are similar issues but I wasn't able to find one with the exact same issue as me.
I have an API which gets SQL data from a SQL server, that data is then send to the client as JSON.
The API returns the following:
[{"text1":"value1","text2":"value2"}]
I am trying to parse both values using the following java code:
which gives me the following error:
type org.json.JSONArray cannot be converted to JSONObject
private void jsonParse() {
String url = "http://192.168.0.197/api.php";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String text1 = obj.getString("text1");
String text2 = obj.getString("text2");
mTextViewResult.append(text1 + ", " + text2 + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}```
in your method Parameter onResponse() you are passing a JSONObject instead of JSONArray. Convert that to either String parameter or JSONArray
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
String text1 = obj.getString("text1");
String text2 = obj.getString("text2");
mTextViewResult.append(text1 + ", " + text2 + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Do not use JSONArray jsonArray = new JSONArray(response) , because response is already a JSONArray.

Getting string from Json

I am new in json.My question is very simple.I have some array in my json file and also a string type of data.
Now I want to get the single text, name: anounce in my java class from json file.
How can i get this string from json ?
or any other way to get this ?
Json file
[{
"title": "KalerKantha | OfftechIT",
"image": "",
"link": "http://www.kalerkantho.com/"
}, {
"title": "Prothom Alo | OfftechIT",
"image": "",
"link": "http://www.prothom-alo.com/"
},
...
{
"anounce": "I need this this text"
}
]
Java Code
JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the Grid view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
hidePDialog();
Toast.makeText(getActivity(), " No Internet connection! \n Please check you connection", Toast.LENGTH_LONG).show();
}};
});
You simply make check the announce is present in the JSON or not
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
if(obj.has("anounce"))
{
String anounce= obj.getString("anounce");
}
else
{
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use optString method. It would return the value if node exists and String.empty is node is not found.
From Documentation
public String optString (String name)
Returns the value mapped by name if it exists, coercing it if necessary, or the empty string if no such mapping exists.
Do this
try {
JSONObject obj = response.getJSONObject(i);
String announce = obj.optString("anounce");
Movie movie = new Movie();
movie.setTitle(obj.optString("title"));
movie.setThumbnailUrl(obj.optString("image"));
movie.setLink(obj.optString("link"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
Update: Using optString is much better, but if you don't want to use it then do this
try {
JSONObject obj = response.getJSONObject(i);
if(i == response.length() -1)
{
String announce = obj.getString("anounce");
}
else
{
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
The Structure of your JSON is hard. But if you really want to get the string. Try this. Add this inside in for loop.
String data = (obj.getString("announce") != null) ? obj.getString("announce") : "";
// If you Movie has this annouce in your settler Getter if not try to add it.
Movie.setAnnounce(data);
Your code look like good but Are you add the request to queue
like:-
AppController.getInstance().addToRequestQueue(movieReq);
movieReq is JsonArrayRequest,
Please check it. and
String manounce=obj.getString("anounce");

Unable to Get Friend List Android

The following code i am using for Getting Friend List From Facebook, I have Session in Another class But Session data comming in this class properly . But after Request for getting Friend list from Facebook. i am getting graphObject {data:[] Just like this .. After that getting JArry Null..
//Class For Getting FacebookUserdata
private void getFacebookUserData() {
Log.d(Utilities.logg, "getFacebookUserData");
//Getting Session information
Log.d(Utilities.logg, "session=" + session);
Request requests;
//Making request for getting Friend list
requests = new Request(session, "me/friends", null, HttpMethod.GET,
new Request.Callback() {
//On Complete Request
public void onCompleted(Response response) {
// threadForUI();
GraphObject graphObject = response.getGraphObject();
FacebookUserDataClass userData = null;
try {
JSONObject json = graphObject.getInnerJSONObject();
//Exit from Dailog
if (json != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mrootInnerInviteFriendsInitiateWars
.setVisibility(RelativeLayout.VISIBLE);
mrootInnerInitiateWars
.setVisibility(RelativeLayout.INVISIBLE);
}
}
//Array for getting data
JSONArray JArray = json.getJSONArray("data");
for (int i = 0; i < JArray.length(); i++) {
if (i == 10) {
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
setListAdapte(mChoose);
}
//Set Json Object for getting all friends
JSONObject innerObject1 = JArray.getJSONObject(i);
//.get(i);
//Geting Pojo Class
userData = new FacebookUserDataClass();
userData.setUserId((String) innerObject1
.getString("id"));
userData.setUserName((String) innerObject1
.getString("name"));
mFacebookUserDataListFull.add(userData);
}
placeFcaebookList();
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
// if(Utilities.getSharedPref(Utilities.API_regId,
// "").isEmpty())
// {
// getSelfFacebookProfile();
// }
//Storing data into local database
Utilities.database
.insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
mckbCheckAll.setChecked(true);
checkUncheckAll(mChoose, true);
mbtnRefreshInviteFriend.setEnabled(true);
Utilities.foolFlag = false;
Utilities.saveFriendListOnServer(
mFacebookUserDataListFull,
Utilities.FACEBOOK);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION1 " + e.toString());
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION2 " + e.toString());
e.printStackTrace();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
Utilities.errorFlag = true;
// onClickFacebookButton();
}
}
});
pendingRequest = false;
requests.executeAsync();
// Utilities.database
// .insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
// Utilities.foolFlag = false;
// Utilities.saveFriendListOnServer(mFacebookUserDataListFull,
// Utilities.FACEBOOK);
// Log.d(logg, "frnds loding done");
// getFacebookImages();
//Getting Image from the Image Class
new GetFacebookImagesUrl().execute();
}

How to cast JSONObject to integer ?

i have a problem how to cast JSONObject or String to integer..
I send data once as a JSONObject
#GET
#Produces(MediaType.APPLICATION_JSON)
public JSONObject sayJSONHello() {
JSONArray numbers = new JSONArray();
numbers.put(1);
numbers.put(2);
numbers.put(3);
numbers.put(4);
JSONObject result = new JSONObject();
try {
result.put("numbers", numbers);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
And one as a String
#Path("/test")
public class Hello {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String sayJSONHello() {
String myString =null;
try
{
myString = new JSONObject().put("data", "1 2 4").toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
return myString;
}
Then, i have problem how to receive this data as a Int.
I tried like this (Client):
Syste m.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).get(String.class));
System.out.println(service.path("rest").path("test").accept(MediaType.APPLICATION_JSON).get(String.class));
String k = service.path("rest").path("test").accept(MediaType.APPLICATION_JSON).get(String.class);
// ERROR int temp = Integer.parseInt(k);
Could anyone advise how to deal with it ?
Your variable k is storing the whole JSON. You would need to parse the JSON object first and then pull out the specific integer (I assume in the array?) that you want.

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories