How to pull individual pieces of data from a JSON to string? - java

public static void main(String[] args) throws IOException {
try {
JSONObject json = new JSONObject(readUrl("http://api.wunderground.com" +"/api/106c4dee47162999/history_20060405/q/CA/San_Francisco.json"));
JSONObject data = json.getJSONObject("observations.tempm");
System.out.println(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private static String readUrl(String string) throws IOException {
BufferedReader reader = null;
try {
String urlString = string;
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
2.errors :
org.json.JSONException: JSONObject["observations.tempm"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at org.json.JSONObject.getJSONObject(JSONObject.java:553)
at com.parser.ParserObject.main(ParserObject.java:17)

The intersting part of the JSON you use is:
{'history':
{'observations':
[
{'tempm':'10.0'}
]
}
}
Use this:
JSONObject json = ...;
JSONObject history = (JSONObject) json.get("history");
JSONArray observations = (JSONArry) json.get("observations");
JSONObject observation0 = (JSONObject) observations.get(0);
String tempm = observation0.get("tempm");
If you are interested in other array elements, use a different index.

'observations' isnt in root. you need to get 'history' first. 'observations' is a part of 'history'. and 'observations' is a list/array.

i suggest using 'jackson' or 'gson' library.parsing native json is really a pain.
you can even go to a extent of un/marshalling only required fields/objects from JSON.

Related

G suite account get report java sample question

I am trying to use this api to get report with java, and here is the link
https://developers.google.com/admin-sdk/reports/v1/appendix/activity/meet
and here is what i am using now
public static String getGraph() {
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try {
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + "access_token");
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(
new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null) {
sbLines.append(strLine);
}
graph = sbLines.toString();
}
} catch (IOException ex) {
x.printStackTrace();
}
return graph;
}
I am pretty sure it's not a smart way to do that and the string I get is quite complex, are there any jave sample that i can get the data directly instead of using java origin httpRequest
Or, are there and class I can import to switch the json string to the object!?
Anyone can help?!
I have trying this for many days already!
Thanks!!

JSON Object GSON into list

I want to implement my old code when I was populating JSON array into listview but my current json haven't specified array, overall json is an array...
Can somebody tell me how to transform my code to use JSON like this?
https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2
Code to use gson, my old:
protected List<Model> 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 = new JSONArray("arrayname");
List<Model> dataModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Model modelList = gson.fromJson(finalObject.toString(), Model.class);
dataModelList.add(modelList);
}
return dataModelList;
} 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;
}
Instead of doing this:
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
Just do this:
JSONArray parentArray = new JSONArray(finalJson);
If i understand the problem correctly, i guess you are having trouble parsing the array who's name is not specified with a key. So, a simple but not a very good way of doing this would be, when you create your finalJson like this:
String finalJson = buffer.toString();
just add a line to check if it contains an array opening bracket, like this:
if(finalJson.contains("[")){
finalJson = finalJson.replace("[","{
"arrayname": [");
}
also, close the array appropriately.
if(finalJson.contains("]")){
finalJson = finalJson.replace("]","]
}");
}
This way, u will have a name for the array to parse, and i guess this is what you are looking for. But this approach might fail if you have more than 1 array in your Json, in that case you will have to use startsWith & endsWith string methods to give a name to your array. But, as of now, from what your Json looks like, this would work.

How to extract multiple JSON Objects into String

I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}

Parse HTTP JSONObject response in java

From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether

org.json.JSONException: End of input at character 0 of while creating a JSON Object

I'm simply trying to create JSON object like that:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get());
Error occurs here ^ with message received in catch block:
org.json.JSONException: End of input at character 0 of
JsonUtility class as follows (I belive problem lies not there but still):
private class JsonUtility extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try {
InputStream inputStream = new URL(params[0]).openStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
// Reading Json into StringBuilder
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
// Converting Json from StringBuilder to String
result = sBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
You see that response is concatenated from strings (due to application logic). The final string is: http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction. As you see when I redirect to that link it gives JSON response.
I have tried to evaluate this UrlUtility.url and received that:
That weird ending of char array confuses me. Perhabs its the problem. Tried to replace those characters using String.replaceAll("'\u0000'0", "" ). Didnt work.
Please help. Will appreciate any ideas. Thanks.
EDIT:
Also, when I hardcode link as:
JSONObject jsonObject = new JSONObject(new JsonUtility().execute("http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction").get());
It works!
EDIT #2 # ρяσѕρєя K
result = sBuilder.toString(); is empty - "" since it can't parse that concatenated string.
Note: I've been using the same parser with different links in this application e.g. http://itvdn-api.azurewebsites.net/api/courses and that was working fine (but there was no concatenation with link)
/**
* Convert InputStream into String
* #param is
* #return
* #throws IOException Throws an IO Exception if input stream cannot be read
*/
public static String stringFromInputStream(InputStream is) throws IOException {
if (is != null) {
byte[] bytes = new byte[1024];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = is.read(bytes)) >= 0)
x.append(new String(bytes, 0, numRead));
return x.toString();
}
else {
return "";
}
}
Use this method for reading the inputstream and get the string.

Categories

Resources