Hi I am working on a project it will show USD EUR TRY Bitcoin Gold values i have api for all of this values in json i want to sort them out my json link is this https://canlidoviz.com/doviz-kurlari.jsonld
I am parsing the json with this class
public class ClassJSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
public ClassJSONParser(){
}
public JSONObject getJSONFromURL(String url) {
try {
URL urlObject = new java.net.URL(url);
HttpURLConnection conn=(HttpURLConnection) urlObject.openConnection();
conn.setRequestMethod("GET");
is = new BufferedInputStream(conn.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
String tmp = line + "/n";
sb.append(tmp);
}
is.close();
json=sb.toString();
}catch (Exception e){
Log.i("Buffer Error","Error Converting Result"+e.toString());
}
try {
if(json !=null){
jObj=new JSONObject(json);
}else{
jObj=null;
}
}catch (JSONException e){
}
return jObj;
}
}
and getting a string like this
ClassJSONParser jParser = new ClassJSONParser();
String url = "https://canlidoviz.com/doviz-kurlari.jsonld";
jsonO= jParser.getJSONFromURL(url);
Log.d("***",jsonO.toString());
what method should i use how can i do can you give me guidance
Related
I am trying to loop through a json object I pulled through the web but I can't seem to convert it from a string to a jsonarray or jsonobject. I want to be able to use a for loop to iterate through it and then conditionally output names based on some values.
This is a simple java program to demonstrate pulling json data from a web api and then looping through it.
Here's the code:
public static List<String> getUsernames(int threshold) throws IOException {
List<String> usernames = new ArrayList<>();
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("url to json api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//Request method
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
usernames.add(line);
}
// String json = new Gson().toJson(usernames);
//
// JSONArray jsonarray = new JSONArray(json);
// System.out.println(json);
Gson gson = new Gson();
reader.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return usernames;
}
List<String> usernames = new ArrayList<>();
usernames.add("Hibernate");
usernames.add("spring");
JSONArray jsonStr = new JSONArray().put(usernames);
for (Object values: jsonStr) {
System.out.println(values);
}
I want wrote an API in php for using it in my android app. In the php side I do this for return info in an array
echo json_encode($array)
result of this code is like this, see online result in this link:
{"value":[{"id":"1","name":"kufta","meal":"1","photo_id":"","explanation":"xoshmazas","foodtime":"0000-00-0000:00:00"},{"id":"2","name":"\r\nAsh","meal":"2","photo_id":"","explanation":"sdfdsfsdfdsfdsfsdf","foodtime":"2017-06-26 14:00:00"},{"id":"3","name":"kabab","meal":"3","photo_id":"","explanation":"kabab kheili khoshmaze ast","foodtime":"2017-06-29 00:00:00"}]}
but in java side when I load this, app crash but when I use this json string in this site. Android app works fine
my java code for reading the url content
public class WebService {
private String connectToServer(String address, String requestMethod) {
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
return inputStreamToString(httpURLConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = reader.readLine()) != null) {
stringBuilder.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
line 23 : public List<FoodModel> getFoods(){ <-----------Error is here
String response = connectToServer("http://mtg1376.gigfa.com/api/food?day=All","GET");
if(response != null){
List<FoodModel> foodList = new ArrayList<😠);
try{
JSONObject mainObject = new JSONObject(response);
JSONArray foodArray = mainObject.getJSONArray("value");
for(int i = 0 ; i< foodArray.length();i++){
JSONObject foodObject = foodArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.id = foodObject.getString("id");
foodModel.name = foodObject.getString("name");
foodModel.meal = foodObject.getString("meal");
foodModel.photo_id = foodObject.getString("photo_id");
foodModel.explanation = foodObject.getString("explanation");
foodModel.foodtime=foodObject.getString("foodtime");
foodList.add(foodModel);
}
return foodList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null; }
}
java error log : https://ibb.co/hQneXk
whats the problem?
Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.
My purpose is to parse twitter data which is described in JSON file. I created a void for parsing JSON which function perfectly, but it show me only one JSONObject while my `
public void parsingJson( String d) throws Exception
{
BufferedReader br = null;
//JSONObject rootObejct=null;
JSONObject js=new JSONObject();
try {
String sCurrentLine;
InputStream inputStream = new FileInputStream("E://inputdata.json") ;
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
br = new BufferedReader(inputStreamReader);
while ((sCurrentLine = br.readLine())!= null) {
JSONObject rootObejct=new JSONObject(sCurrentLine);
for(#SuppressWarnings("unchecked")
Iterator<String> iter = rootObejct.keys();iter.hasNext();) {
String key = iter.next();
try {
if (key.startsWith(d)){
System.out.println("******key*********"+key);
Object value = rootObejct.get(key);
System.out.println("keys vlaue "+value.toString());
}
} catch (JSONException e) {
// Something went wrong!
}
}
}
`
Here's a simple code to read a JSON file
public void readJSONFile(String filePath) {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filePath));
JSONObject jsonObject = (JSONObject) obj;
//if your value is an array
JSONArray arr = (JSONArray) jsonObject.get("array");
//if your value is string
String str = (String) jsonObject.get("status");
} catch (Exception e) {
e.printStackTrace();
}
}
JSON file used as test case is
{
"status": "OK",
"array": [ "Hello" ]
}
If it doesn't help, please let me know.
I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.