I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way.
Is this really the best I can do?
HttpResponse response; // some response object
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
JSONArray finalResult = new JSONArray( tokener );
I'm on Android if that makes any difference.
Two things which can be done more efficiently:
Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
Use BufferedReader#readLine() to read it line by line instead of reading it char by char.
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
If the JSON is actually a single line, then you can also remove the loop and builder.
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
Use JSON Simple,
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
You can do something like this,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
You can use the Gson library for parsing
void getJson() throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("some url of json");
HttpResponse httpResponse = httpClient.execute(httpGet);
String response = EntityUtils.toString(httpResponse.getEntity());
Gson gson = new Gson();
MyClass myClassObj = gson.fromJson(response, MyClass.class);
}
here is sample json file which is fetchd from server
{
"id":5,
"name":"kitkat",
"version":"4.4"
}
here is my class
class MyClass{
int id;
String name;
String version;
}
refer this
Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
Instead of doing
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
You can do:
JSONTokener tokener = new JSONTokener(
IOUtils.toString(response.getEntity().getContent()) );
where IOUtils is from the commons IO library.
For Android, and using Apache's Commons IO Library for IOUtils:
// connection is a HttpURLConnection
InputStream inputStream = connection.getInputStream()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStream, baos);
JSONObject jsonObject = new JSONObject(baos.toString()); // JSONObject is part of Android library
There is no need to do the reader loop yourself. The JsonTokener has this built in. E.g.
ttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new
JSONTokener tokener = new JSONTokener(reader);
JSONArray finalResult = new JSONArray(tokener);
Related
Please help
I am trying to fetch all tests associated with Execution in JIRA XRAY
I am getting java.lang.IllegalStateException: Not a JSON Object error at step mentioned in last below(element.getAsJsonObject();)
String urlString=baseServerURL+"/rest/raven/latest/api/testexec/"+executionCycleKey+"/test";
System.out.println(urlString);
HttpURLConnection con = getConnection(urlString, "GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine.toString());
content.append(inputLine);
}
in.close();
con.disconnect();
Gson g = new Gson();
JsonElement element = g.fromJson(content.toString(), JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
Note: inputLine prints as [{"id":100806,"status":"TODO","key":"ST_MABC-1234","rank":1}]
Actually, the response is an array of JSON objects. Therefore you cannot parse it as JSON object.
You'll need to use the JSONArray class instead.
Example:
String raw = "[{\"id\":100806,\"status\":\"TODO\",\"key\":\"ST_MABC-1234\",\"rank\":1} ]";
System.out.println(raw);
JSONArray arr = new JSONArray(raw);
System.out.println( ((JSONObject)(arr.get(0))).get("id"));
In my project , i separated back-end and front-end modules and run by providing REST api from back-end and call it by using Apache Http Client and GSON.
I want to provide multiple language like German,French... on UI(webpage).
On webpage , It shows like this "Schl��ssli Sch��negg, Wilhelmsh��he" , but in database and RestAPI json is "Schlössli Schönegg" .
How can I support multi language?
In back-end , i wrote Request methods like get,put,post and In Front-end, i used HttpClient and GSON to convert JSON to/from Java Object.
I tried inside the html but main problem is from GSON when it convert fromJSON() , the original JSON value ""Schlössli Schönegg" become "Schl��ssli Sch��negg, Wilhelmsh��he".
In RestAPI , JSON data is
{
"addressId": 3,
"buildingName": "Schlössli Schönegg",
"street": "Wilhelmshöhe",
"ward": "6003",
"district": "luzern",
"cityOrProvince": "luzern state",
"country": "Switzerland"
}
But in Front-end , Java Object String Data after GSON convert is
(..buildingName=Schlössli Schönegg, street=Wilhelmshöhe, ward=6003, district=luzern, cityOrProvince=luzern state, country=Switzerland)
Here , RestClient function code
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(URL);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;
}
Inside Employee, I have address atrribute , inside that address i have value like buildingNumber and Street, that value can be in any languages.
Try with this
(BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));)
Entire Code will end up with like this.
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(url);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8")); // if it is not working please try with ("ISO-8859-1")
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;}
Next time make sure to try with this, because you can use "try with resource"
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new URL("https://htt.your url.com" + URLEncoder.encode(query, "UTF-8") )
.openConnection().getInputStream()))) {
I have this request in Java but in the response i haven't all source, and Json object fail..
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://url?"+params);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
String str = result.toString();
Document doc = Jsoup.parse(str);
JSONObject json = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
Element elementsTable = doc.getElementById("shortlist");
this element shortlist can't find that..but if i go with my browser and get the source there is..where i'm wrong?
You can do it with Jsoup with simpler code ...
Connection connection = Jsoup.connect(url)
Document urlDoc = connection.get();
Elements domElement = urlDoc.getElementById(String id);
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());
So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());