I am using a HttpURLConnection to get Json from a web into a string.
And i'm storing web string into BufferedReader and after that storing it in a new String.
And string is here:-
{"coord":{"lon":72.85,"lat":19.01},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":302.131,"pressure":1024.24,"humidity":84,"temp_min":302.131,"temp_max":302.131,"sea_level":1024.75,"grnd_level":1024.24},"wind":{"speed":4.77,"deg":302.001},"clouds":{"all":12},"dt":1459677392,"sys":{"message":0.0102,"country":"IN","sunrise":1459645229,"sunset":1459689786},"id":1275339,"name":"Mumbai","cod":200}
How can i convert it into JsonObject.
I've also seen this answer (How to convert String to JsonObject) but it's not working.
Here is code:-
BufferedReader br= new BufferedReader(new InputStreamReader(conn.getInputStream()));
String localoutput;
while ((localoutput = br.readLine()) != null)
{
output=localoutput+output;
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e);
}
JsonReader jsonReader = Json.createReader(new StringReader(output));
JsonObject object = jsonReader.readObject();
jsonReader.close();
try {
String cityname = object.getString("name");
System.out.println(cityname);
}
catch (Exception e)
{
e.printStackTrace();
}
Here output is the String which I've mentioned it earlier.
I'm not getting the Output Cityname in my console.
Use this library. It provides very simple API, to convert a String to json object simply do the following:
try {
JSONObject object = new JSONObject(yourJsonString);
} catch (Exception e){
e.printStackTrace();
}
Related
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
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.
Previously, i can access the string from php remotely. I find it difficult at first but AsyncTask did the work for me. Now, i can access the result of the query from php to sql server. But I would like to pass a string from my java class to php and as I googled some information, i saw some JSON post and get codes but i can't clearly understand them. Here's my code:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
The string is contained in "sb.toString()". Now how would I add a JSON something in my code to send string from java to php, and also get the result string from php to java as well. Thanks in advance for any help.
If you receive response as JSON format from server, make the json string to JSONObject first. And then read the json data for your use.
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
Your code already contains the answer of your question. After make url connection, just add parameter for sending your data to server with OutputStreamWriter as like you did for receive the response with InpustStreamReader.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here
I am trying to extract data from Json string which is obtained by a response using only Java code.
I am posting my Java code here.
OUTPUT:
Entering into while loop
[{"name":"Frank","food":"pizza","quantity":3}]
This is my Java code.
public void receive()
{
System.out.println("Entering into sendNote method");
try {
// make json string,
String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";
// send as http get request
URL url1 = new URL("http://myurl/file.php?usersJSON="+userList);
URLConnection conn1= url1.openConnection();
//I am receiving exactly what I have sent....
BufferedReader rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
System.out.println("Entering into while loop");
System.out.println(line);// line contains the received json parameters
//I want to enter the recieved parameters into my database
//
//
//
//I need the solution right here....
}
rd.close();
}
catch (Exception e)
{
System.out.println("Error Occured while receiving");
e.printStackTrace();
}
}
Thank you !!!!!
#Ankur:
This is how I tried,
# Lahiru Prasanna, #ankur-singhal
Thanks a lot.!!
I think that you successfully got HttpResponse.here variable called response is HttpResponse.
// Could do something better with response.
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
content.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(builder.toString());
} catch (JSONException e) {
System.out.println("Error parsing data " + e.toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
System.out.println( "" + e.toString());
System.out.println("" + e.toString());
}
And important thing is never use Strings for json operations.
you can retrieve your data from jsonObject like this
String name = jsonObject.getString("name");
There are few ways to achive the same.
1.) Create a response pojo
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);
// then call getters on above.
2.) Get key/values
JSONObject json = (JSONObject)new JSONParser().parse(""name":"Frank","food":"pizza","quantity":3}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("food"));
3.) Converting Json to HashMap
public static void main(String[] args) {
try {
jsonToMap("{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : " + jObject);
System.out.println("map : " + map);
}
output
json : {"name":"Frank","food":"pizza","quantity":3}
map : {food=pizza, name=Frank, quantity=3}
I am currently parsing through reddit.com/.json with Google Gson and having some trouble. After doing some research I found a way to parse through json with Gson without making a lot of classes. I am using this method. Here is my code so far:
import java.io.*;
import java.net.*;
import com.google.gson.*;
public class Subreddits {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null){
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();//String of json
System.out.println(json);
//I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("data").getAsJsonObject("children").getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
System.out.println(subreddit);
}
}
You are trying to get the element "children" as a JsonObject, but it is a JsonArray because it is surrounded by [ ]...
Try something like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
//Here is the change
JsonObject locObj = rootObj
.getAsJsonObject("data")
.getAsJsonArray("children")
.get(0)
.getAsJsonObject()
.getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
Note: I assume that you only want to get the data of the first element of the "children" array, since it seems that it is what you want looking at your code and mainly looking at this other question of yours.
The children object returns an Array that you must iterate.
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null) {
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();// String of json
System.out.println(json);
// I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray locObj = rootObj.getAsJsonObject("data").getAsJsonArray("children");
/* Iterating children object */
Iterator<JsonElement> iterator = locObj.iterator();
while(iterator.hasNext()){
JsonElement element = iterator.next();
JsonElement subreddit = element.getAsJsonObject().getAsJsonObject("data").get("subreddit");
System.out.println(subreddit.getAsString());
}
}
You don't need to create try..catch block for every expression that can throw an exception.
JsonParser.parse() method accepts Reader (e.g. InpustStreamReader) instance so you don't have to read JSON on your own.
root[data][children] is an array of objects so you'll have to iterate over them in order to gain access to individual objects.
I believe you want to read all [subredit]s into some sort of collection, Set I pressume?
public static void main(String[] args) {
try {
Set<String> subreddits = new HashSet<>();
URL url = new URL("http://www.reddit.com/.json");
JsonParser parser = new JsonParser();
JsonObject root = parser.parse(new InputStreamReader(url.openConnection().getInputStream())).getAsJsonObject();
JsonArray children = root.getAsJsonObject("data").getAsJsonArray("children");
for (int i = 0; i < children.size(); i++) {
String subreddit = children.get(i).getAsJsonObject().getAsJsonObject("data").get("subreddit").getAsString();
subreddits.add(subreddit);
}
System.out.println(subreddits);
} catch (IOException e) {
e.printStackTrace();
}
}
This code returns:
[IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]