JSON:
{
"deviceId": "AAAAAAA1",
"cardInfo": {
"pan": "123456789012345",
"psn": "00",
"cvv": "123",
"panExpiryDate": "2017-12-12"
},
"productType": "CREDIT",
"requestor": 1234,
"aid": "A000000001234567",
"aidVersion": 1,
"panSource": null,
"deviceLanguage": "en"
}
Android Code:
protected String doInBackground(Void... params) {
Bundle bundle=getIntent().getExtras();
final String newdata=bundle.getString("newdata");
try {
js=new JSONObject(newdata);
di=js.getString("deviceId");
} catch (JSONException e) {
e.printStackTrace();
}
postDataParams = new HashMap<String, String>();
postDataParams.put("deviceId",deviceID);
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
postDataParams.put("productType",productType);
postDataParams.put("requestor",requestor);
postDataParams.put("aid",aid);
postDataParams.put("aidVersion",aidVersion);
postDataParams.put("panSource",panSource);
postDataParams.put("deviceLanguage",deviceLanguage);
response = service.postServerData(path,postDataParams);
try {
json = new JSONObject(response);
System.out.println("success " + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
On writing this code am not getting any response from the url. Can you please help where i did the mistake.
Change this
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
to this
JSONObject cardInfoJson = new JSONObject();
cardInfoJson.put("pan", card);
cardInfoJson.put("psn", psn);
cardInfoJson.put("cvv", cvv);
cardInfoJson.put("panExpiryDate", panExpiryDate);
postDataParams.put("cardInfo", cardInfoJson);
Related
I try to get information from this link
and I don't get it !
This is my code:
String s = getJSONFile();
String myDataArray[] = {};
try{
JSONObject reportJSON = new JSONObject();
JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");
myDataArray = new String[dateJSON.length()];
for (int i = 0; i <dateJSON.length(); i++){
JSONObject jsonObject = dateJSON.getJSONObject(i);
myDataArray[i] = jsonObject.getString("terrestrial_date");
}
}catch (JSONException e){
e.printStackTrace();
}
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
if (mListView != null){
mListView.setAdapter(stringAdapter);
}
}
this is the getJSONFile method:
public String getJSONFile() {
String json = null;
try {
InputStream is = getResources().openRawResource(R.raw.weather_json);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Thanks for help :)
You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/
This is so easy.
terrstial_date is a String of report. try this,
String date=jsonObject.getString("terestial_date");
also your json parsing structere is not correct accroding to your json
{
"report": {
"terrestrial_date": "2017-10-13",
"sol": 1844,
"ls": 73.0,
"min_temp": -81.0,
"min_temp_fahrenheit": -113.8,
"max_temp": -28.0,
"max_temp_fahrenheit": -18.4,
"pressure": 869.0,
"pressure_string": "Higher",
"abs_humidity": null,
"wind_speed": null,
"wind_direction": "--",
"atmo_opacity": "Sunny",
"season": "Month 3",
"sunrise": "2017-10-13T10:59:00Z",
"sunset": "2017-10-13T22:43:00Z"
}
}
This is how you can get response from OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://marsweather.ingenology.com/v1/latest/?format=json")
.get()
.build();
try {
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONObject reportJson = jsonObject.getJSONObject("report"); // your report object.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Put your Json file in your assets folder with .json extension and use this method to get JsonString from it
public String loadJSONFromAsset(String fileName) {
String json = null;
try {
InputStream is = getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And get the String using this function like this
String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");
and Parse like that
try{
JSONObject responce = new JSONObject(jsonString);
JSONArray report= responce.getJSONObject("report");
String terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
this is my code after all the change:
public void find_weather() {
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("results");
JSONArray array = response.getJSONArray("");
JSONObject object = array.getJSONObject(0);
String date = object.getString("date");
String tempMin = String.valueOf(main_object.getDouble("min_temp"));
String tempMax = String.valueOf(main_object.getDouble("max_temp"));
String atmo_opacity = object.getString("atmo_opacity");
mMaxTemp.setText("max_temp");
mMinTemp.setText("min_temp");
mAtmoOpacity.setText("atmo_opacity");
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
String formatted_data = sdf.format(calendar.getTime());
mDate.setText(formatted_data);
double temp_max_int = Double.parseDouble(tempMax);
double temp_min_int = Double.parseDouble(tempMin);
mMaxTemp.setText(String.valueOf(i));
mMinTemp.setText(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
You are doing in wrong way
1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data
2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data
For, more information get a look here How to parse JSON in Android
Try this,
String s = getJSONFile();
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(s);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
EDIT
Try, Volley for fetching JSON data
First you need to add dependency of volley in build.gradle file-:
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Then use following code to fetch or parse your JSON data
// Tag used to cancel the request
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(response);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Volley.newRequestQueue(this).add(strReq);
SCREENSHOT
As, You can see the screenshot above. I am getting response with the same code
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
{"Sam":{"status":"available","classkey":"dotnet"}}
How to parse this type of json?
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
domtdl = jObj.getString(dom);
try {
JSONObject c = new JSONObject(domtdl);
if(c != null){
status = c.getString(TAG_STATUS);
System.out.println(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Is it correct?
I do not know how to get data from second JSON object.
Please help me.
For this specific json string {"Sam":{"status":"available","classkey":"dotnet"}}
you need to do
try {
JSONObject jObj = (new JSONObject(json)).getJSONObject("Sam");
String status = jObj.getString("status");
String classkey = jObj.getString("classkey");
} catch (JSONException e) {
e.printStackTrace();
}
try
{
JSONObject jb = new JSONObject(myjsonstring);
JSONObject job = jb.getJSONOBject("Sam");
String status = job.getString("status");
Log.i("Status is",status);
String classkey = job.getString("classkey");
Log.i("Class Key is",classkey);
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{ represents a json object node
{ // json object node
"Sam": { // json object SAM
"status": "available", json string
"classkey": "dotnet" json string
}
}
JSON Tutorial #
http://www.w3schools.com/json/
Your json can also look like below sometimes.
[ represents json array node
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
To parse the above
StringBuilder sb = new StringBuilder();
try {
JSONObject jb = new JSONObject(myjsonstring);
JSONArray jarr = jb.getJSONArray("employees");
for(int i=0;i<jarr.length();i++)
{
JSONObject job = jarr.getJSONObject(i);
String firstname = job.getString("firstName");
String lastname = job.getString("lastName");
sb.append(firstname);
Log.i("firstname",firstname);
sb.append("\n");
Log.i("lastname",lastname);
}
Toast.makeText(getApplicationContext(), sb, 10000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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 :)
Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.
The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");
use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java