From the endpoint "test" I am returning a JSONObject:
#POST("/test")
#PermitAll
public JSONObject test(String name) {
JSONObject jsonval=new JSONObject();
json.put("key1",true);
json.put("key2","test");
return json;
}
in the method that checks the returned value I want to search for value of "key1".
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = null;
String res = "";
while ((res = in.readLine()) != null) {
json += res + "\n";
}
in.close();
if (jsonData has key1 with value true){
//do sth
}
else{
//do sth else
}
How can I parse the returned JSONObject?
Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html):
JSONObject result = new JSONObject(json)
where json is the string you've read from the InputStream
Note: you might have to strip the last new line char or even omit new lines altogether
Related
I created a post request with json and it works pretty well. But now I want to insert the output of this json post request into my database.
So I need to create a json parser to seperate the string like this: "Bestellnummer:1", "Besteller:8195529", "Zeit: 2019-09-27 15:50:07", "Artikelnummer:76194", "Anzahl:1", "Preis:2.968"... (next Artikelnummer and so on...).
Bestellnummer = orderid, Besteller = customerid, Zeit = time, Artikelnummer=articleid, Anzahl = number of article, Preis= price
I tried to do something like a parser in my code, but I never did something like this befor and unfortuntly don't know how to involve this parser in my code.
I hope u can help me
One example for my json Output:
{"Bestellnummer":"1","Besteller":"8195529","Zeit":"2019-09-27 15:50:07","Artikel":[{"Artikelnummer":"76194","Anzahl":"1","Preis":"2.968"},{"Artikelnummer":"61681","Anzahl":"1","Preis":"7.147"},{"Artikelnummer":"111756","Anzahl":"1","Preis":"9.29"},{"Artikelnummer":"14227","Anzahl":"1","Preis":"0"}]}
Code:
private static String dirPath = "https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php";
public ArrayList<String> Bestellung(){
File file = new File (dirPath + "//array_complex.json");
ArrayList <String> test = new ArrayList<String>();
try {
String str = "{ \"Bestellnummer\": [1,2,3,4,5] }";
// holt alle 47550 bestellungen vom json
for (int i=1; i<2;i++) {
String POST_PARAMS = "json={\"bid\":\"bid\", \"getorder\":\""+i+"\"}";
//System.out.println(POST_PARAMS);
JSONObject obj1 = new JSONObject(POST_PARAMS);
JSONArray arr=obj1.getJSONArray("Bestellnummer");
for (int z=0; z<arr.length();z++) {
String post_id = arr.getJSONObject(z).getString("Bestellnummer");
System.out.println(post_id);
}
URL obj = new URL("https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("connection", "Keep-Alive");
postConnection.setDoOutput(true);
java.io.OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
//System.out.println("POST Response Code : " + responseCode);
// System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
test.add(response.toString());
// java.util.Iterator<String> it = test.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
}
}
}
catch (Exception e) {
System.out.println();
}
return test;
}
If what you want to do is to insert the HTTP response string into database, I strongly recommend you to deserialize the string to POJOs as follows:
Declare 2 classes - MyResponse and Artikel. Artikel is for storing the content of JOSN object in JSON array, and I use List<Artikel> for the JSON array. BTW, I also use #JsonProperty(provided in Jackson) to map JSON keys with uppercase to variables with lowercase.
class MyResponse {
#JsonProperty(value="Bestellnummer")
private String bestellnummer;
#JsonProperty(value="Besteller")
private String besteller;
#JsonProperty(value="Zeit")
private String zeit;
#JsonProperty(value="Artikel")
private List<Artikel> artikel;
//general getters and setters
}
class Artikel {
#JsonProperty(value="Artikelnummer")
private String artikelnummer;
#JsonProperty(value="Anzahl")
private String anzahl;
#JsonProperty(value="Preis")
private String preis;
//general getters and setters
}
Now, you can use Jackson (one of the most popular JSON libraries) to deserialize the HTTP response to our POJOs. And you can manipulate these POJOs for DB operation easily.
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(response.toString(), MyResponse.class);
myResponse.getArtikel().forEach(System.out::println);
Console output
Artikel [artikelnummer=76194, anzahl=1, preis=2.968]
Artikel [artikelnummer=61681, anzahl=1, preis=7.147]
Artikel [artikelnummer=111756, anzahl=1, preis=9.29]
Artikel [artikelnummer=14227, anzahl=1, preis=0]
Because you provided too less information to come up with a more detailed answer I came up with the following code.
JSONObject main = new JSONObject(data);
String orderNumber = main.getString("Bestellnummer"); // Retrieving the order number
String orderUserId = main.getString("Besteller"); // Retrieving the orderUserId
String time = main.getString("Zeit"); // Retrieving the current time
JSONArray articles = main.getJSONArray("Artikel"); // Getting articles as JSON Array
for (int i = 0; i < articles.length(); i++) { // Looping tough the articles
JSONObject article = articles.getJSONObject(i); // Getting the article JSON Object
String articleNumber = article.getString("Artikelnummer"); // Retrieving the Article number
String amount = article.getString("Anzahl"); // Retrieving the amount
String price = article.getString("Pris"); // Retrieving the price
// Your code...
}
I hope this helps you.
I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
null object reference with String"json"
I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose
But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)
You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI
You are appending the string to StringBuilder sb = new StringBuilder();. You have to call like this parseJSON(sb.toString()); cause String json is just a pointer doesn't hold the actual string, you want.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String json = sb.toString();
You can instead use my code snippet it's working fine for me. now you can use son variable for your private void parseJSON(String json) function.
I am using gson library to get the json from an http request.
Everything works fine, except the part where I compare the string I received from the request. Even if the string are exactly the same, for some reason string.equals method fails. And as output it prints always different dates.
What is the reason for this behaviour? What am I missing here?
BufferedReader br;
try{
String url = "http://date.jsontest.com/";
URL request_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)request_url.openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()){
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String jsonLine = "";
String line ;
while ((line = br.readLine()) != null) {
jsonLine += line;
}
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
try{
String result = jobject.get("date").toString();
System.out.println("res: " + result);
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
}
catch (NullPointerException ex){ }
}
}
catch (JsonSyntaxException ex){}
catch (IOException ex) {}
String result = jobject.get("date").toString();
The above line returns String representation of date, i.e. with quotes around it : "05-29-2017" and that's why equals method returns false ("\"05-29-2017\"".equals("05-29-2017") will be false due to double quotes in the start and end)
If you want the actual value, you need to use getAsString method, e.g. following should work:
String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}
I am returning a json from my class:
#POST("/test")
#PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream" and parse it to see if key1 exists:
String output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
output=output.toString();
JSONObject jsonObj = new JSONObject();
jsonObj.put("output", output);
if (jsonObj.get("output") != null){
**//search for key1 in output**
System.out.println("key1 exists");
}else{
System.out.println("key1 doesnt exist");
}
reader.close();
How can I convert output to JSONObject and search for "key1"?
I tried following but I got errors after arrows:
JSONObject jObject = new JSONObject(output); ---> The constructor JSONObject(String) is undefined
JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
And then you can verify the existence of the field using:
jsonObject.has("key1");
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples