i'm calling a Rest API in GET, and i need to parse the response and take the value of a key.
I'm using:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
This is my code:
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((readLine = in.readLine()) != null) {
sb.append(readLine);
}
JSONObject jsonObject = new JSONObject(sb.toString());
jsonObject.get();
in.close();
But in JSONObject jsonObject = new JSONObject(sb.toString()); generate a error
Error:(32, 63) java: incompatible types: java.lang.String cannot be converted to java.util.Map
Thanks so much.
You should be using JSONParser to get the data from String:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(sb.toString());
JSONObject is used to serialize its data into JSON string via toJSONString() method.
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 am trying to get from a json username this is the json
[{"user_id":"1","username":"THEUSERNAME","count300":"0","count100":"0","count50":"0","playcount":"0","ranked_score":"0","total_score":"0","pp_rank":"0","level":"0","pp_raw":"0","accuracy":"0","count_rank_ss":"0","count_rank_s":"0","count_rank_a":"0","country":"0","events":[]}]
My code is
URL url = new URL("url");
URLConnection c = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder b = new StringBuilder();
String line;
while ((line = in.readLine()) != null) b.append(line);
String text = b.toString();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(text);
String username = (String) jsonObject.get("username");
System.out.println(username);
And the error i get
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at eu.dpp.ircbot.Ircbot.main(Ircbot.java:80)
Note the [] around your original string. This indicates that it's a JSONArray and not a JSONObject, which is exactly what the exception you get tells you. For the JSON specs, see http://json.org/
The actual object is surrounded with {}, you may be confused because you only have 1 object inside the array. But you still have to treat the string as an array and then iterate over the objects in it.
i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code :
URL url = new URL("SOME URL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
JSONObject jObject = new JSONObject(output);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
MY string contain
{"data":{"name":"New Product","id":1,"description":"","is_active":true,"parent":{"id":0,"name":"All Projects"}}}
this is the string which i want in json but it shows me Exception in thread "main"
java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:83)
at org.json.JSONObject.<init>(JSONObject.java:310)
at Main.main(Main.java:37)
The name is present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.
JSONObject jObject = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.
Note: This example uses the org.json.JSONObject class and not org.json.simple.JSONObject.
As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.
Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.
Sample from the link provided:
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-
StringBuilder buffer = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
buffer.append(output);
}
output = buffer.toString(); // now you have the output
conn.disconnect();
Converting the String to JsonNode using ObjectMapper object :
ObjectMapper mapper = new ObjectMapper();
// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)
// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)
// For Json String
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);
Instead of JSONObject , you can use ObjectMapper to convert java object to json string
ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
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);