Java and simple json - java

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.

Related

JIRA Xray- Not a JSON Object error while making Rest API call to get Execution details

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"));

Parse JSON array of objects from url Java

How do I parse an array of JSON objects from an external URL with the Java application? Here is an example of code, that I am using:
URL connectionUrl = new URL(/*some url*/);
connection = (HttpURLConnection) connectionUrl.openConnection();
String postData = "/*some post data*/";
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(postData.length());
OutputStream outputStream = null;
outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes());
if(connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String magicString = "", magicLine;
while((magicLine = bufferedReader.readLine()) != null) {
JSONArray jsonArr = new JSONArray(magicLine);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject currentEntity = jsonArr.getJSONObject(i);
}
}
return magicString;
And this one is the array of JSON objects, that gets echo'd out on some external URL:
[{"ID":"1","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"0"},{"ID":"2","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"1"}]
Unfortunately, the application fails with the following error:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONArray
You can create a POJO to hold JSON response. Use third-party jar such as Jackson. Something like the following:
ObjectMapper mapper = new ObjectMapper();
try {
YourPOJO obj = mapper.readValue(new URL("http://jsonplaceholder.typicode.com/posts/7"), YourPOJO.class);
System.out.println(usrPost);
} catch (Exception e) {
e.printStackTrace();
}
Refer to https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/

Convert Buffered Reader in JSONObject (json-simple)

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.

Java String to JSON conversion

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);

Json from C# to JAVA

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());

Categories

Resources