So far I can send a Get request to a server with a letter added to the url :
private void GetDevice() {
String deviceId = editTextDeviceId.getText().toString().trim();
if(TextUtils.isEmpty(deviceId)){
editTextDeviceId.setError("Please enter deviceId");
editTextDeviceId.requestFocus();
}
HashMap<String, String>params = new HashMap<>();
params.put("deviceID", deviceId);
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_GETBYDEVICEID + deviceId, null, CODE_GET_REQUEST);
request.execute();
}
When I press the button Search it sends the request :
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetDevice();
}
});
The server response is JSONArray :
W/System.err: org.json.JSONException: Value [{"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"}] of type org.json.JSONArray cannot be converted to JSONObject
Here is my problem.
From what I read, I know I need to use an ArrayList and ArrayAdapter to convert it into a JSONObject. Am I right so far ?
Here is where I’m stuck, as I don’t understand how to do it.
Many thanks in advance!
The JSON string returned from the server is a Json array,
so you need to convert it to a Jsonarray as follows, the jsonString here is the JSON string returned.
try {
JSONArray array=new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
The param you send is a JSONArray ,and the param that the server needs is a JSONObject.
The structure of JSONObject is like { },and a JSONArray is like [ { } , { } , ...... , { } ].So, you can change your param to {"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"} or edit the code of the server to receive parameters with JSONArray.
Try this:
You need to add array adapter
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
String deviceID=json_data.getString("deviceID");
items.add(deviceID);
Log.d(deviceID,"Output"+deviceID);
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item, items));
setListAdapter(mArrayAdapter);
add device id in Hashmap it works
Related
I am creating a REST API using Spring Boot and using org.json for parsing data retrieved from another different service. From this service I am getting JSON data like in following format
{
"my_data":[
{
"user_data":{
"first_name":"FirstTest1",
"last_name":"LastTest1",
"age":"25"
}
},
{
"user_data":{
"first_name":"FirstTest2",
"last_name":"LastTest2",
"age":"35"
}
},{
"user_data":{
"first_name":"FirstTest3",
"last_name":"LastTest3",
"age":"45"
}
}
],
"count":10,
"is_safe":false
}
and I have to transform received data to the following JSON
[
{
"user_data":{
"first_name":"FirstTest1",
"last_name":"LastTest1",
"age":"25"
}
},
{
"user_data":{
"first_name":"FirstTest2",
"last_name":"LastTest2",
"age":"35"
}
},{
"user_data":{
"first_name":"FirstTest3",
"last_name":"LastTest3",
"age":"45"
}
}
]
I know I can use a POJO to map the data and send it (already doing this) but here the issue is that the data received from another service is not fixed e.g. it may or may mot have "first_name" or may have a different field like "country". So, in this situation I can not make POJO beforehand.
After going through some online resources I made some changes and my POST Controller method looks like this.
#PostMapping(path = "/searchusersdata")
public RETURN_SOMETHING searchUsersData(#RequestBody Map<String, String> searchData) {
List<JSONObject> finalDataCollection = new ArrayList<JSONObject>();
//Making some REST API CALL TO GET 'response' using 'searchData'
String someResponse = response.getBody();
JSONObject object = null;
try {
object = new JSONObject(someResponse);
} catch (JSONException e) {
e.printStackTrace();
}
String my_data= object.get("my_data").toString();
JSONArray intermediateJA = null;
intermediateJA = new JSONArray (my_data);
for(int i = 0; i < intermediateJA.length(); i++) {
JSONObject item = intermediateJA.getJSONObject(i);
if (item.keySet().contains("user_data"))
{
Object value = item.get("user_data");
finalDataCollection.add(new JSONObject(value));
}
}
//WHAT TO RESTURN HERE
}
Now, I don't know what to return hare. For a single JSONObject we can use return new ResponseEntity<>(return_data.toMap(), HttpStatus.OK); but for a collection I don't know. I am open to suggestion if I have to do it in entirely different way. I also know that with gson or jackson it might be easier but I have to use org.json.
instead of List , use JsonArray and use ResponseEntity to return it.
Example
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonArray.put(jsonObject);
return new ResponseEntity( jsonArray.toString(), HttpStatus.OK);
I am using Fast-Android-Networking and I want to send data to server which contains strings and arrays. It's ok to send string but I am unable to send array its not array list. It's simple array.
I have search other solution but all are regarding volley.
can anyone help?
Please dont mark duplicate.
The last 5 parameters are arrays. I tried it as String.valueOf(ReadQuran) but it also didn't work.
My Code:
AndroidNetworking.post(Api.ROOT_URL +"api/stageFiveFormData")
.addBodyParameter("mto_id",idu)
.addBodyParameter("school_id", scholid)
.addBodyParameter("person_name", personnameS)
.addBodyParameter("designation", designantionS)
.addBodyParameter("cell_number",personcellS)
.addBodyParameter("email",emailpersonS)
.addBodyParameter("whatsapp_number",whatsApppersonS)
.addBodyParameter("school_name",schoolNameS)
.addBodyParameter("postal_address",postalAdressS)
.addBodyParameter("city",cityS)
.addBodyParameter("tehsil",tehsilS)
.addBodyParameter("district",districtS)
.addBodyParameter("s_primary", priamryChecked)
.addBodyParameter("s_middle", middleChecked)
.addBodyParameter("s_high", highChecked)
.addBodyParameter("s_higher", hsChecked)
.addBodyParameter("principal_name", nameOfPrincipalS)
.addBodyParameter("p_contact_num",cellNoPrincipalS)
.addBodyParameter("p_email",emailPrincipalS)
.addBodyParameter("p_whatsapp_number",whatsAppPrincipalS)
.addBodyParameter("class", Class)
.addBodyParameter("rq_book", String.valueOf(ReadQuran))
.addBodyParameter("rqb_qty", String.valueOf(ReadQuranQty))
.addBodyParameter("fq_book", String.valueOf(FehamQuran))
.addBodyParameter("fqb_qty", String.valueOf(FehamQuranQty))
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String result = jsonObject.getString("result");
String message = jsonObject.getString("message");
if (result.equalsIgnoreCase("success")) {
Toast.makeText(FormStage5.this, "" + message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(FormStage5.this, formstage2submittedmsg.class);
startActivity(intent);
pDialog.dismiss();
} else/* (result.equalsIgnoreCase("0"))*/ {
Toast.makeText(FormStage5.this, ""+message, Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
} catch (JSONException e) {
pDialog.dismiss();
Toast.makeText(FormStage5.this, "Something Went Wrong , Try Again", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(FormStage5.this, "Please Check Your Internet Connection" + anError.toString(), Toast.LENGTH_LONG).show();
pDialog.hide();
}
});
The best way is to create a POJO class and set Array value, then pass it. It will automatically gets converted into JSON, if you are using retrofit with GSONConverter factory.
The accepted answer to this question talks about Retrofit and GSON, while the question is about Fast Android Networking. The accepted answer did not work for me.
I found that the only way to do this was to build the body myself and add it to the request with .addJSONObjectBody.
I wanted a body that looks like:
{
"roles": [
"customer-admin"
]
}
The final way I found which works is:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
JSONObject roles;
try {
roles = new JSONObject();
JSONArray rolesArr = new JSONArray();
rolesArr.put("customer-admin");
roles.put("roles", rolesArr);
} catch (JSONException e) {
// Make error toast here
return;
}
AndroidNetworking.post(url)
.addJSONObjectBody(roles)
.build()
pass the arrayname.toString() as a value
I have to send the json array to web server. I have created json array from array list. I have a helper class which sends json object to server.
So I want to convert the json array to json object.
I tried to do this:
Async Task:
public class SendMultipleInvitesAsyncTask extends AsyncTask<String, Void, JSONObject> {
private Context context;
JSONArray array = new JSONArray();
public SendMultipleInvitesAsyncTask(Context context)
{
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendMultipleInvite.php";
JSONObject obj = new JSONObject(params[0]);
ServerRequest request = new ServerRequest(api,obj);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
Activity :
public class SendMultipleInvites extends AppCompatActivity {
private ArrayList<Invitation> invitationArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_multiple_invites);
invitationArrayList = new ArrayList<>();
Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");
invitationArrayList.add(invitation);
invitation = new Invitation("3","17/02/2016","282751221","1","user10");
invitationArrayList.add(invitation);
// JSONArray jsArray = new JSONArray(invitationArrayList);
Gson gson=new Gson();
String toServer=gson.toJson(invitationArrayList);
new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(toServer);
But this gives me an error that json object can not be converted to json array.
I want to send input of json array like this:
{
"invitations": [
{
"sender_id" : 3,
"date" : "12/08/2016",
"invitee_no" : "196756456",
"status" : "1",
"user_name" : "user10"
},
{
"sender_id" : 3,
"date" : "12/08/2016",
"invitee_no" : "13633469",
"status" : "1",
"user_name" : "user9"
}
]
}
How can I do this? How to pass it through an async task. Or what is going wrong here? Please help Thank you..
invitationArrayList is your ArrayList so jo get a JSON array. If you want to wrap this array in a JSON object you have to this in java as well.
For example:
String toServer = gson.toJson(
Collections.singletonMap("invitations", invitationArrayList)
);
(assumed that gson.toJson works as expected. I'm no gson expert because I'm mostly use jackson...)
JavaDoc for Collections.singletonMap: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singletonMap(K,%20V)
i have a request to build slider image from jsonArray using volley, i don't know how to put value of jsonArray to hashmap<string, string> .. it keep saying null object
error message
Attempt to invoke virtual method 'java.lang.Object
java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
JSON array value
[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]
and then i wanna put that value like this into hashmap<string, string> inside onCreate()
HashMap<String,String> url_maps = new HashMap<>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
it gonna use for adding picture to my slider(slideshow) inside onCreate()
for(String name : url_maps.keySet()){
DefaultSliderView DefaultSliderView = new DefaultSliderView(getContext());
// initialize a SliderLayout
DefaultSliderView
.image(url_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
DefaultSliderView.bundle(new Bundle());
DefaultSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(DefaultSliderView);
}
and i don't know how to put values from volley JsonArray, and this is my request but error saying null.
private void getSlider(){
String tag_string_req = "sliderList";
// Showing progress dialog before making http request
JsonArrayRequest mostReq = new JsonArrayRequest(AppConfig.URL_Slider, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < 5; i++) {
JSONObject jObj = response.getJSONObject(i);
url_maps.put(jObj.getString("cPID"), jObj.getString("image"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + "Error Data Occured!!" + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) ;
AppController.getInstance().addToRequestQueue(mostReq, tag_string_req);
}
the values request was accepted on volley, it show on Logcat .. but null on hashmap .. tell me if i got mistake in my code, sorry just newbie and still study
You are iterating thru just the keys... You need to iterate through the keys and values...
for (url_maps.Entry<String, String> url_map : url_maps.entrySet()) {
String key = url_map.getKey();
String value = url_map.getValue();
// ...
}
ANOTHER WAY TO ATTEMPT THIS IS...
to deserialize your Json into a java object...
ObjectMapper mapper = new ObjectMapper();
string StringJson = "[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]";
// For the following line to work you will need to make a URLMaps Class to hold the objects
URLMaps urlMaps = mapper.readValue(StringJson , URLMaps.class);
The URLMaps Class might look like this.
public class URLMaps{
public string name = "";
public string image = "";
//constructor
public URLMaps(string a, string b) {
name = a;
image = b;
}
public string getName() {
return name;
}
public string getImage() {
return image;
}
}
Then to utilize the class you can go with:
urlMaps.getName(), or urlMaps.getValue() in your DefaultSliderView.image()
Also to note, since this is a class you can store an array of them or a list of them, so you can re-purpose your for loop...
For (URLMap urlmap : UrlMaps[]) // where URLMaps is your object that holds multiple instances of URLMaps.
Lastly, it has been a long time since I have coded in Java, so this code is untested, but should help you come to a solution.
I'm trying to parse the JSON located at http://api.pathofexile.com/ladders/Default?offset=0&limit=1.
{
"total": 15000,
"entries": [
{
"online": false,
"rank": 1,
"character": {
"name": "Byrr",
"level": 85,
"class": "Shadow",
"experience": 1397076236
},
"account": {
"name": "Canoobians"
}
}
]
}
I've been following the androidhive tutorial while attempting to modify it to retrive the "online" and "rank" elements. (Eventually I want all of the elements with large numbers of entries, but I'm starting with just those two to try to understand things.
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.pathofexile.com/ladders/Default?offset=0&limit=2";
// JSON node names
private static final String TAG_ENTRIES = "entries";
private static final String TAG_ONLINE = "online";
private static final String TAG_RANK = "rank";
// entries JSONArray
JSONArray entries = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> entriesList = new ArrayList<HashMap<String, String>>();
// create JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from url
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of entries
entries = json.getJSONArray(TAG_ENTRIES);
// looping through entries
for (int i = 0; i < entries.length(); i++) {
JSONObject ent = entries.getJSONObject(i);
// storing each JSON item in a variable
String online = ent.getString(TAG_ONLINE);
String rank = ent.getString(TAG_RANK);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ONLINE, online);
map.put(TAG_RANK, rank);
// adding HashList to ArrayList
entriesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, entriesList, R.layout.list_item, new String[] { TAG_ONLINE, TAG_RANK }, new int[] { R.id.online, R.id.rank });
setListAdapter(adapter);
My JSONParser() class is the same as in the tutorial. Now when I run the program I get the error:
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject.
I don't know why this error is happening since the JSON is valid according to JSONLint, so it shouldn't be sending any HTML, correct? Is there something I'm missing, or even a completely different/better way to extract the JSON? Any kicks in the right direction would be greatly appreciated.
EDIT : I can't self answer yet since I'm a new user, but It turns out that I was getting a NullPointerException in JSONParser() that I didn't see before, and using HttpGet() rather than HttpPost() solved my problem.
Thanks.
Look at this line in JSONParser
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Site returns this header
Content-Type: text/html; charset=UTF-8
You have to change iso-8859-1 to UTF-8 in BufferedReader.
It turns out that I was getting a NullPointerException in JSONParser() that I didn't see before and using HttpGet() rather than HttpPost() solved my problem.