I have to create JSON parser to save data received from url into JSON object using org.json library and only java standard libraries but I have no idea how to connec to those
String line = "326";
URL oracle = new URL("https://api.tfl.gov.uk/Line/"+line+"/Arrivals?app_id=&app_key=");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
This my connection code
My suggestion would be to use a JSON parser such as Jackson.
Create a class that would store the data you want to store from
that JSON.
Use URL to connect and grab the JSON
Use Jackson to convert it to a Java object
Let me know if you need more help and I can provide it.
Use an http client library like okhttp to make the request and get the string body.
Then use a json parser like Jackson to parse the received string into Json object.
Use okhttp as below:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response resp = client.newCall(request).execute();
String response = resp.body().string();
Once you have the response string you can make a jsonNode from it by using Jackson ObjectMapper as below
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(response);
Or get your defined POJO by parsing the response as
YourClass mappedPOJO = mapper.readValue(response, YourClass.class);
Lets say your incoming json was
{
"key1":"value1",
"key2": {
"key3":"value3"
}
}
Then tree.get("key1") gives you "value1",
tree.get("key1").get("key2") gives you "value3"
Related
I'm writting an Java application that do requests through REST API to Named Entity Recognition service (deeppavlov) running in a local network.
So I request data by following:
String text = "Welcome to Moscow, John";
List<String> textList = new ArrayList<String>();
textList.add(text);
JSONObject json = new JSONObject();
json.put("x", textList);
String URL = "http://localhost:5005/model";
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL))
.header("accept", "application/json")
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(json.toString()))
.build();
try {
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
System.out.println(response.body().getClass());
} catch (IOException | InterruptedException e) {
}
As result I get:
[[["Welcome","to","Moscow",",","John"],["O","O","B-GPE","O","B-PERSON"]]]
class java.lang.String
It is a string and I don't know how to convert it to object, array, map or list to iterate through. Please help.
It depends from the library that you are using to deserialize the string.
It seems that you are using org json code, so a possible solution uses a JSONTokener:
Parses a JSON (RFC 4627) encoded string into the corresponding object
and then use the method nextValue:
Returns the next value from the input. Can be a JSONObject, JSONArray, String, Boolean, Integer, Long, Double or JSONObject#NULL.
The code will be the following
Object jsonObject = new JSONTokener(jsonAsString).nextValue();
I want to get just ID from httpResponse after I did HttpGet.
This is my code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
which returns this:
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}
But I just want Oid not the whole thing. Any idea?
Thanks
Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:
gson
JsonSimple
Jackson etc.
My favorite for small projects is gson
Using Jackson or Gson, you can parse the response JSON and get exactly the part you need.
If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, e.g.
mapper.readTree(responseText).get("foo").get("bar")
I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:
try {
JSONObject obj = new JSONObject(your_json_string);
String value= null;
if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
value = obj.getString(YOUR_KEY_FOR_PARAM));
}
}
I have an Activity which has three fragments and I am trying to retrieve a JSON file from my server which I will be updating on a daily basis.
My JSON file is located here: http://pagesbyz.com/test.json
Because there are fragments, I used the following code in my MainActivity class:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
What I really need to do is retrieve the TYPE field in my JSON file and separate it into three tabs and put it inside a ListView like this:
I would like to know once I have read the JSON file by using the code on top how do I proceed... Thanks for the help :)
Should I query on each fragment and then look for the TYPE field? Would that be easier?
Curious as to why the Toast did not execute... Here is the pastebin for my main activity: http://pastebin.com/gKTCeH79
What you want to do is use Androids JSONObject and JSONArray to access your json data.
For example since your root is a json array you want to instantiate a JSONArray object from your json data you have.
JSONArray jsonArray = new JSONArray(jsonString);
Now from this array you can grab individual JSONObject for each object in your array.
JSONObject objectOne = new JSONObject(0); // Grabs your first item
From the JSONObject you can now access your three values.
String type = objectOne.get("type") // Will give you the value for type
JSONArray: http://developer.android.com/reference/org/json/JSONArray.html
JSONObject: http://developer.android.com/reference/org/json/JSONObject.html
Another way is to use a framework that lets you deserialize json into Java POJO's (Plain Old Java Objects). Gson is the easiest to use.
The basic idea is you make an object that relates directly to your json objects, after you have this you can easily store your data in java objects and use it however you like.
GSON example:
Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);
Where MyCustomClass would contain the variables id, type, and data.
GSON reference: https://sites.google.com/site/gson/gson-user-guide
Good Luck!
I have a web application in C#, and I use JsonSerializer to create a json.
Now I'm wotrking on an android application and I'm trying to read the json.
On my Android application, my code is
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "application/json; charset=utf-8");
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page); // here it explodes
}
It get explodes when trying to create a json object, because the value of "page" is
"{\\"Key\\":\\"1\\",\\"RowVersion\\":[0,0,0,0,0,0,226,148].....
When I try to get the json on the browser manually (with direct GET url), I get
"{\"Key\":\"1\",\"RowVersion\":[0,0,0,0,0,0,226,148]......
When I copy this string manually it works fine.
How can I fix it?
You are returned a JSON object as a String whereas you expected a JSON object...
With Jackson, this is easily solved:
final ObjectMapper mapper = new ObjectMapper();
// JSON object as a string...
final JsonNode malformed = mapper.readTree(response.getEntity().getContent());
// To JSON object
final JsonNode OK = mapper.readTree(malformed.textValue());
Either this, or fix the server side so as to return the JSON object!
I think that your code it too complicated, try do it like this:
String page = EntityUtils.toString(response.getEntity());
I am using the low level API to get an HTTPResponse object as the response to my get request to a URL(an API function).
What is the quick and easy way to parse the content of that object? The response will be a JSON response, and I want to use Google GSON to convert that JSON data into Java object...
How do I accomplish this?
If your response is a string, you can do:
if (response.getCode() == 200){
String result = new String(response.getContent(), "UTF-8");
if (result != null){
Gson gson = new Gson();
YourObject obj = gson.fromJson(result,YourObject.class);
}
}