I am new on JAVA, how to parse the countryname using this API: https://iplist.cc/api
Use JAVA to parse the JSON: https://iplist.cc/api
Get ONLY the "countryname" value.
For example,
If the country name is "countryname": "Germany",
The OUTPUT should be only:
Germany
I tried this but did not work :(
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
// url to make request
private static String url = "https://iplist.cc/api";
// JSON Node names
private static final String COUNTRY_NAME = "countryname";
// contacts JSONArray
JSONArray contacts = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
country = json.getString(COUNTRY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}
Thank You!
For such deserialization purpose, I would recommend you to use Gson (or another of this kind).
implementation 'com.google.code.gson:gson:2.8.6'
Prepare IP class for deserialization:
public class IP {
public final String ip;
public final String registry;
public final String countrycode;
public final String countryname;
public final String detail;
public final boolean spam;
public final boolean tor;
public IP(String ip, String registry,
String countrycode, String countryname,
String detail, boolean spam, boolean tor) {
this.ip = ip;
this.registry = registry;
this.countrycode = countrycode;
this.countryname = countryname;
this.detail = detail;
this.spam = spam;
this.tor = tor;
}
}
Deserialize from JSON String with Gson:
IP ip = new Gson().fromJson(json, IP.class);
System.out.println(ip.countryname);
First add org.json library to your project. this is for converting String to JSONObject.
public class HttpGet {
public static String readGetRequestData(String urlToRead) throws IOException {
// System.setProperty("https.proxyHost", "ip");
// System.setProperty("https.proxyPort", "port"); if you got some proxy set it
URL url = new URL(urlToRead);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
return new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String data = readGetRequestData("https://iplist.cc/api");
try {
JSONObject jsonObject = new JSONObject(data);
System.out.println(jsonObject.get("countryname"));
} catch (JSONException err) {
err.printStackTrace();
}
}
}
result is: Germany
Related
Im trying to have a few getter methods for a few strings to get returned after getting them from an online JSON. In order to save space I decided to put that all in an object and call them from there.
Object:
public class InventoryItem extends AsyncTask<Void,Void,Void>{
String imageURL = "";
String itemName = "";
String itemDesc = "";
String itemRarity = "";
String itemType = "";
JSONObject itemJson = null;
InventoryItem(JSONObject json){
itemJson = json;
Log.d("StringSubclass","Inventory Item");
}
#Override
protected Void doInBackground(Void... voids) {
Log.d("StringSubclass","doInBG Inventory Item");
try {
imageURL = "http://www.bungie.net"+itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("icon");
Log.d("StringSubclass",imageURL);
itemName = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemName");
itemDesc = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemDescription");
itemRarity = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("tierTypeName");
itemType = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemTypeName");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public String getItemType() {
return itemType;
}
public String getItemRarity() {
return itemRarity;
}
public String getItemDesc() {
return itemDesc;
}
public String getItemName() {
return itemName;
}
public String getImageURL() {
return imageURL;
}
}
The problem is that the getter methods at the end send back "" even though I changed their value in doInBackground.
This is how I called getImageURL():
InventoryItem subclass = new InventoryItem(makeJSON(HOST+"Manifest/6/"+subclassHash+"/"));
subclass.execute();
Log.d("StringSubclass",subclass.getImageURL());
intentHome.putExtra("SubclassImageURL",subclass.getImageURL());
makeJSON():
public JSONObject makeJSON(String url){
JSONObject json = null;
String apiKey = "36c346318fa54fc6bc659ad6321a6d41";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-API-KEY", apiKey);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
String response = "";
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
JsonParser parser = new JsonParser();
JsonObject gson = (JsonObject) parser.parse(response);
json = new JSONObject(gson.toString());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
I checked the URL and it is working fine in chrome.
Any help will be appreciated.
I kind of new to this so please explain as much as possible.
Thanks
I have this JSON object:
{
"1":{
"id_module":"f83d6101cc",
"adresse_mac":"00:6A:8E:16:C6:26",
"mot_de_passe":"mp0001","name":"a"
},
"2":{
"id_module":"64eae5403b",
"adresse_mac":"00:6A:8E:16:C6:26",
"mot_de_passe":"mp0002",
"name":"a"
}
}
And I would like to parse and get to string id_module, adresse_mac, mot_de_passe and name for each thing the 1 and the 2.
So I made this but it's not working :
TextView txt1=(TextView) findViewById(R.id.textView);
String ajout1 = "http://";
JSONObject json = null;
String str = "1";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(ajout1);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(str);
String MAC = jsonObject.getString("id_module");
txt1.setText(MAC);
} catch (JSONException e) {
e.printStackTrace();
}
You should try this:
String str = "your json string";
JSONObject json = new JSONObject(str);
String module = json.getJSONObject("1").getString("id_module");
String address = json.getJSONObject("1").getString("adresse_mac");
String module2 = json.getJSONObject("2").getString("id_module"); //from 2nd object
First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}
I want to get a JSON object from a Http get response:
Here is my current code for the Http get:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
HttpResponse response;
String result = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
System.out.println("RESPONSE: " + result);
instream.close();
if (response.getStatusLine().getStatusCode() == 200) {
netState.setLogginDone(true);
}
}
// Headers
org.apache.http.Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
Here is the convertSteamToString function:
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Right now I am just getting a string object. How can I get a JSON object back.
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
Do this to get the JSON
String json = EntityUtils.toString(response.getEntity());
More details here : get json from HttpResponse
This is not the exact answer for your question, but this may help you
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
Without a look at your exact JSON output, it's hard to give you some working code. This tutorial is very useful, but you could use something along the lines of:
JSONObject jsonObj = new JSONObject("yourJsonString");
Then you can retrieve from this json object using:
String value = jsonObj.getString("yourKey");
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject, then first get a String from the result:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject:
JSONObject jsonObject = new JSONObject(jsonString);
You need to use JSONObject like below:
String mJsonString = downloadFileFromInternet(urls[0]);
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
...
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}
catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
Hope this helps you..
There is a JSONObject constructor to turn a String into a JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
If your api is response is a java object, then the string that you got from Outputstream should be in json string format such as
{\"name\":\"xyz\", \"age\":21}
. This can be converted to JSON object in many ways, out of which one way is to use google GSON library.
GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); <javaobject> = gson.fromJson(<outputString>, <Classofobject>.class);
One can do it without Gson also, using Jackson, which implements Json Tree Model.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);
1)String jsonString = EntityUtils.toString(response.getEntity());
2)JSONObject jsonObject = new JSONObject(jsonString);
I am not sure why this url is throwing a MalformedURL exception: http%3A%2F%2Fapi.themoviedb.org%2F3%2Fsearch%2Fperson%3Fapi_key%3secret%26query%3Dchristopher_guest
This is the url required by the api that I need to use. http://api.themoviedb.org/3/search/person?api_key=secret&query=christopher_guest
I have been getting target host must not be null errors using this url then I changed my coded to what you are seeing below. Not sure whats going on here although I have heard urls that contain underscores dont validate outside of web browsers and cause these types of situations.
Any ideas around this?
This is where I build the url
package com.tot.tipofthetongue;
import android.widget.EditText;
public class getName {
static String nameOne = null;
static String nameTwo = null;
static StringBuilder personURLOne = new StringBuilder();
static StringBuilder personURLTwo = new StringBuilder();
public static String personURL = "http://api.themoviedb.org/3/search/person?api_key=secret&query=";
public static StringBuilder getName1(EditText searchOne){
nameOne = searchOne.getText().toString();
nameOne = nameOne.replace(" ", "_");
personURLOne.append(personURL);
personURLOne = personURLOne.append(nameOne);
return personURLOne;
}
And this is my jsonparser that I pass that url to.
public class JSONParser extends AsyncTask<String, Void, JSONObject> {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public String myURL;
String host;
HttpRequest request;
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
//Make HTTP Request
try {
//defaultHttpClient
for(int i = 0; i < url.length; i++){
myURL = url[0];
myURL = URLEncoder.encode(myURL, "utf-8");
}
HttpGet httpGet = new HttpGet(myURL);
//header
httpGet.setHeader("Accept", "application/json");
HttpResponse httpResponse = new DefaultHttpClient().execute(new HttpHost(new URL(myURL).getHost()), request);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
Log.d("JSON Contents", stringBuilder.toString());
inputStream.close();
jSon = stringBuilder.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
Print the String you formed before final submission to form Uri. And attach this to your question. It would be much easier to answer.
Try using HttpGet(URI uri) instead of HttpGet(String uri)
The reason is pretty simple. If you are using Uri, you will get immediately the Exception.
Hope this will help you to debug quickly.