Java String to JSON conversion - java

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

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/

Java and simple json

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.

How to put JSON information in an array to use it for displaying in ListView

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!

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