Android JSON Parser - java

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.

Related

How to pass array values in JSON?

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);

How to use ArrayAdapter and JSONArray for a listView

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

Any method of passing the Json data in URL format using JSONObject?

I create a java URL class which contain my Json data and have some function to obtain back my json data for doing some data comparison, I found out it's might not support by JSONObject for passing the data into the JSONObject. Do I need to use JSONArray in my case because my JSON data have array structure as well?
try
{
JSONObject obj = new JSONObject ();
obj.readJsonFromUrl(theUrl);
System.out.println(obj.toString());
}
catch(MalformedURLException e)
{
System.out.print("your problem here ...1");
}
}
else
{
System.out.print("Can't Connect");
}
I am sure that this is the place give me the error message because it return me this error in my compiler
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method readJsonFromUrl(URL) is undefined for the type JSONObject
there are also some warning message for that the JSONObject readJsonFromUrl method
private static JSONObject readJsonFromUrl(URL theUrl) throws IOException, JSONException {
Anyone can provide me the explaination of how the JSON data work in java? I saw quite number of Java class for JSON which make me confuse for it such as JSONObject, JSONArray , JSONValue. I search some information online but I also not very clear about it since I am very new to JSON data processing This is my sample json data and the data I need is scan_result only
{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"file_info":{
"display_name":"",
"file_size":242,
"file_type":"Not available",
"file_type_description":"Not available",
"md5":"aa69ba384f22d0dc0551ace2fbb9ad55",
"sha1":"09ceb54e65df3d3086b222e8643acffe451a6e8a",
"sha256":"dcb46d6ae2a187f789c12f19c44bbe4b9a43bd200a3b306d5e9c1fcf811dc430",
"upload_timestamp":"2016-11-18T09:09:08.390Z"
},
"process_info":{
"blocked_reason":"",
"file_type_skipped_scan":false,
"post_processing":{
"actions_failed":"",
"actions_ran":"",
"converted_destination":"",
"converted_to":"",
"copy_move_destination":""
},
"profile":"File scan",
"progress_percentage":100,
"result":"Allowed",
"user_agent":""
},
"scan_results":{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"progress_percentage":100,
"scan_all_result_a":"No Threat Detected",
"scan_all_result_i":0,
"scan_details":{
"Ahnlab":{
"def_time":"2016-11-08T15:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":1,
"threat_found":""
},
"Avira":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":133,
"threat_found":""
},
"ClamAV":{
"def_time":"2016-11-08T10:28:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":94,
"threat_found":""
},
"ESET":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":38,
"threat_found":""
}
},
"start_time":"2016-11-18T09:09:08.405Z",
"total_avs":4,
"total_time":250
},
"vulnerability_info":{
}
}
As mentioned here, there are many ways to solve this. Either you have to implement the read, parse operations yourself (#Roland Illig 's answer)
//you have to implement the readJSON method
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
Or you could use a library. The most well-known and widely used libraries are jackson and gson.
The big picture is that you try to "map" your json Object to a class.
You have your json file:
{
"id":1,
"name":"eirini",
"hobbies":["music","philosophy","football"]
}
and a class that represents this file and will store the values (depending on the library that you use there might be different requirements, for example getters, setters etc..)
public class Person {
public int id;
public String name;
public List<String> hobbies = new ArrayList<String>();
public String toString() {
return name +" has the id: " + id + " the following hobbies" + hobbies.get(0) + " " + hobbies.get(2);
}
}
Finally in your main method:
public static void main(String[] args) throws IOException, ParseException {
ObjectMapper mapper = new ObjectMapper();
InputStream input = this.getClass().getResourceAsStream(FILE); //read your file. There are many ways to achieve this.
ObjectMapper mapper = new ObjectMapper(); // just need one
Person eirini = mapper.readValue(input, Person.class);
System.out.println(eirini.toString());
You cannot pass json in url, you can pass it in body. Writing Json to stream body and post it using regular java method.
Here is oracle community url of explanation of your problem.
Required Jar can be downloaded from here.
Test Code Follows:
URL url = new URL("https://graph.facebook.com/search?q=java&type=post");
try (InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is)) {
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)){
System.out.print(result.getJsonObject("from").getString("name"));
System.out.print(": ");
System.out.println(result.getString("message", ""));
System.out.println("-----------");
}
}

Convert string to json object gives an error

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)

json array value from volley into hashmap string, string

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.

Categories