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)
Related
ArrayList<StylistArray>stylistsArr=new ArrayList<StylistArray>();
stylistsArr.add(new StylistArray("BqYWKWzs4r8SyGQvyqH2","18:30"));
stylistsArr.add(new StylistArray("at5kjx5FqIxbnMys8w4q","18:30"));
stylistsArr.add(new StylistArray("nFI5hxfIePx240dmqR0R","18:00"));
stylistsArr.add(new StylistArray("spxSj8UZem5uD0wL46EP","18:20"));
.
https://us-central.jshshskajshdala.net?dasa="+"2018-09-04"+"&ewsss="+"17:50"+"&stylist="+String.valueOf(stylistsArr)
I want to pass this arrayList along with the url. When I try to pass the array values the name of the model class is passing instead of values in the class
Example
I want to pass values like this:
[
{
"stylist": "BqYWKWzs4r8SyGQvyqH2",
"endTime": "18:30"
},
{
"stylist": "at5kjx5FqIxbnMys8w4q",
"endTime": "18:30"
},
{
"stylist": "nFI5hxfIePx240dmqR0R",
"endTime": "18:00"
},
{
"stylist": "spxSj8UZem5uD0wL46EP",
"endTime": "18:00"
}
]
Like #Mathan and #Cris say, you can simply using for looping to create your JSON string. For the following simple pojo:
public class StylistArray {
// use a final so the value can't be change once the object is created.
private final String stylist;
private final String endTime;
public StylistArray(String stylist, String endTime) {
this.stylist = stylist;
this.endTime = endTime;
}
public String getStylist() {
return stylist;
}
public String getEndTime() {
return endTime;
}
}
You can simply doing the following:
List<StylistArray> list = new ArrayList<>();
// assume you have add all items to the list.
JSONArray jsonArray = new JSONArray();
try {
// You need to use simple for loop instead the following foreach
// because foreach is slower than traditional loop.
for (StylistArray stylistArray : list) {
// create JSON object for each item
JSONObject jsonObject = new JSONObject();
jsonObject.put("stylist", stylistArray.getStylist());
jsonObject.put("endTime", stylistArray.getEndTime());
// append it to your JSON array.
jsonArray.put(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
// Error happens, try to handle it.
}
Then you can get the string from the JSONArray. I'll let you to find out ;)
Add the Gson dependency in gradle
implementation 'com.google.code.gson:gson:2.8.4'
and rebuild your project
String json= new Gson().toJson(stylistsArr);
Now your "json" variable will have a json array.
Here is the code
List<Map<String, String>> values = new ArrayList<Map<String, String>>();
Map<String, String> maps = new HashMap<>();
maps.put("stylist", "BqYWKWzs4r8SyGQvyqH2");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "at5kjx5FqIxbnMys8w4q");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "nFI5hxfIePx240dmqR0R");
maps.put("endTime", "18:00");
values.add(maps);
JSONArray mJSONArray = new JSONArray(values);
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
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 am working on an Android app and one of its functionnalities is to know when a streamer is streaming by using Twitch API.
When a streamer is streaming, if I connect to https://api.twitch.tv/kraken/streams/ I get a String which I use to build a JSON object like that :
{
"_links":{
"self":"https://api.twitch.tv/kraken/streams/srkevo1",
"channel":"https://api.twitch.tv/kraken/channels/srkevo1"
},
"stream":{
"_id":15361851552,
"game":"Super Smash Bros. for Wii U",
"viewers":42613,
"created_at":"2015-07-18T15:07:59Z",
"video_height":720,
"average_fps":59.319897084,
"_links":{
"self":"https://api.twitch.tv/kraken/streams/srkevo1"
},
"preview":{
"small":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-80x45.jpg",
"medium":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-320x180.jpg",
"large":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-640x360.jpg",
"template":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-{width}x{height}.jpg"
},
"channel":{
"_links":{
"self":"https://api.twitch.tv/kraken/channels/srkevo1",
"follows":"https://api.twitch.tv/kraken/channels/srkevo1/follows",
"commercial":"https://api.twitch.tv/kraken/channels/srkevo1/commercial",
"stream_key":"https://api.twitch.tv/kraken/channels/srkevo1/stream_key",
"chat":"https://api.twitch.tv/kraken/chat/srkevo1",
"features":"https://api.twitch.tv/kraken/channels/srkevo1/features",
"subscriptions":"https://api.twitch.tv/kraken/channels/srkevo1/subscriptions",
"editors":"https://api.twitch.tv/kraken/channels/srkevo1/editors",
"videos":"https://api.twitch.tv/kraken/channels/srkevo1/videos",
"teams":"https://api.twitch.tv/kraken/channels/srkevo1/teams"
},
"background":null,
"banner":null,
"broadcaster_language":"en",
"display_name":"srkevo1",
"game":"Super Smash Bros. for Wii U",
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/srkevo1-profile_image-e46c53476d9b74c7-300x300.png",
"mature":null,
"status":"Evolution 2015 - Main Stage (July 17-19) all brackets http://evo2015.s3.amazonaws.com/brackets/index.html",
"partner":true,
"url":"http://www.twitch.tv/srkevo1",
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/srkevo1-channel_offline_image-ee2fc39d6ebb7735-640x360.jpeg",
"_id":30917811,
"name":"srkevo1",
"created_at":"2012-05-30T16:57:11Z",
"updated_at":"2015-07-18T16:18:40Z",
"delay":0,
"followers":82134,
"profile_banner":null,
"profile_banner_background_color":null,
"views":20938144,
"language":"en"
}
}
}
This is how I get the JSON Object :
public class GetStreamStatus extends AsyncTask<Void,Void,String> {
#Override
protected String doInBackground(Void... params) {
String res = bibixChannel.getJson("streams");
return res;
}
#Override
protected void onPostExecute(String s) {
channelStatusString = s;
channelStatusObject = bibixChannel.buildJSON(s);
}
}
The buildJson() method is simply :
protected JSONObject buildJSON(String jsonRaw){
JSONObject json = null;
try{
json = new JSONObject(jsonRaw);
}catch (Exception e){
e.printStackTrace();
}
return json;
}
But after, to know if the streamer is streaming, a part of the JSON string is nulled like that :
If the streamer is streaming, you will get the fist JSON I wrote on the top of that post, else you will get something like that :
{
"_links":{
"self":"https://api.twitch.tv/kraken/streams/bibixhd",
"channel":"https://api.twitch.tv/kraken/channels/bibixhd"
},
"stream":null
}
What I want to do is getting the "stream" part in another instance variable to either recover infos about the stream or to display an offline message.
What i have got from your OP is that the channelStatusObject return you the JSONObject which contains stream key. Now what you want to check is that whether this stream is null or not. So you could do something like :-
protected JSONObject checkStream(JSONObject parentObject){
JSONObject json = (JSONObject) parentObject.get("stream");
return json; // will return null if stream is null else stream JSONObject
}
You can use this method & check its return value to see if stream is null or not.
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.