Unable to display response from the webservices call in codename one - java

I am getting this JSON response from my webservices
{root:[{name:abc, surname:xyz}]} and I'm trying to display only the Key:Value from the response using label.
I am using the add component method
hi.addComponent(new Label(""+ response.get("/result[0]/ocassion")));
But it's showing me null value. I have followed videos on Webservices available in the codenameone website.
What should i try to get required response to be displayed on the UI.
Here is MyApplication.java code from codename one:
InputStreamReader reader = new InputStreamReader(input);
JSONParser parser = new JSONParser();
response = parser.parse(reader);
System.out.println(""+ response);
hi.addComponent(new Label(""+ response.get("/result[0]/ocassion")));
hi.getComponentForm().revalidate();

Change parse.parse to parse.parseJSON. You have to know the key to retrieve the value, you can loop through your response as follows:
InputStreamReader reader = new InputStreamReader(input);
JSONParser parser = new JSONParser();
response = parser.parseJSON(reader);
List listResponses = (List) response.get("root");
if (listResponse != null) {
for (Object listResponse : listResponses) {
Map tempHash = (Map) listResponse;
hi.addComponent(new Label("Name: " + tempHash.get("name").toString()));
hi.addComponent(new Label("Surname: " + tempHash.get("surname").toString()));
System.out.println(tempHash.get("name").toString()); //Print abc
System.out.println(tempHash.get("surname").toString()); //Print xyz
}
hi.getComponentForm().revalidate();
} else {
System.out.println("null value returned"); //Make sure you reference root and be sure it returns proper json
}

Related

Appending jsonobject to an existing jsonobject

I'm having a problem with Json file reading and writing. I want to append something into a json file but it doesn't work properly: it just put in a new jsonobject without the ',' to divide it from the previous one. I searched everywhere, on every site, but nothing that gave me an input on how to do it properly.
For example, I have a json file like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}
And I want to make it appear like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
So, I tried using this code:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
JsonObject dati = new JsonObject();
dati.addProperty("Cognome", StringUtils.capitalize((fields[0].getText())));
dati.addProperty("Nome", StringUtils.capitalize((fields[1].getText())));
dati.addProperty("Sesso", lblSesso.getText());
dati.addProperty("Luogo di nascita", StringUtils.capitalize((fields[2].getText())));
dati.addProperty("Provincia", lblProvincia.getText());
dati.addProperty("Data di nascita", fieldDDN.getText());
jsonObject.add(codfis, dati);
String json = gson.toJson(jsonObject);
try (BufferedReader br = new BufferedReader(new FileReader("CodFisCalcolati.json"));
BufferedWriter bw = new BufferedWriter(new FileWriter("CodFisCalcolati.json", true))) {
String jsonString = gson.fromJson(br, JsonElement.class).toString();
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobject = jelement.getAsJsonObject();
jobject.add(codfis, dati);
String resultingJson = gson.toJson(jelement);
bw.write(resultingJson);
bw.close();
} catch (IOException e1) { e1.printStackTrace(); }
But when I use it, it give me this output :
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
That's output, you see, it'wrong and i don't know how to make the code to give me a different output.
I'm using Gson 2.8.5 and I would rather not change to another library.
You change the question but now the answer to your new question is you use the same file to read and write. That's why you add the data inside ot the file. Change the name of the file that you write and see if you have problems
Please check if "br" is not null.
According to the specification of the method fromJson it returns:
an object of type T from the string. Returns null if json is null.
If this is the case than you call on the null toString() method and you get null pointer exception

Unexpected token END OF FILE at position 0 while parsing JSON

In order to find out weather the JSON element is JSONArray or JSONObject type, I am getting Unexpected token END OF FILE at position 0 error.
My JSON is:
{"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
My code is:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
System.Out.Println("aaaaaa JSON Class: "+parser.parse(reader).getClass());
if(parser.parse(reader) instanceof org.json.simple.JSONArray)
System.Out.Println("JSONArray");
else if(parser.parse(reader) instanceof org.json.simple.JSONObject)
System.Out.Println("JSONObject");
When I run above code it shows this output
aaaaaa JSON Class: class org.json.simple.JSONObject Unexpected token END OF FILE at popsition 0
at org.json.simple.parser.JSONParser(Unknown Source)
.
.
.
<rest of the exception>
I don't understand why this exception is occurring.
Please help me out.
Some more details after edit:
My this code is working fine with the given json file:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
org.json.simple.JSONObject object = (JSONObject)parser.parse(reader);
System.Out.Println("JSONObject: "+object);
org.json.simple.JSONArray array = (JSONArray)object.get("colors");
System.Out.Println("JSONArray: "+array);
Output of above code:
JSONObject: {"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
JSONArray: [{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]
But I want to dynamically parse the JSON without knowing the JSON structure.
I want to do something like this:
if(json is object)
JSONObject object = (JSONObject)parser.parse(reader);
else if (json is array)
JSONArray array = (JSONArray)parser.parse(reader);
Thanks.
You're repeatedly parsing the same Reader. The first call exhausts it and then each subsequent call sees an empty stream.
Parse the reader only once. Here is the working code:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
Object p = parser.parse(reader);
if(p instanceof org.json.simple.JSONArray){
System.Out.Println("JSONArray");
org.json.simple.JSONArray object = (JSONArray)p;
}
else if(p instanceof org.json.simple.JSONObject){
System.Out.Println("JSONObject");
org.json.simple.JSONObject object = (JSONObject)p;
}
Output of above code
JSONObject
Well, error may occur when you try to pass wrong path.
So check your path to json file properly. Try to use absolute path at first.
Here is my procedure:
private static void ReadWithEncoding(String filePath, String encoding) {
StringBuilder json = new StringBuilder();
File f = new File(filePath);
if (f.exists() && f.isFile()) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), encoding));
String line;
while ((line = br.readLine()) != null) {
json.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(json);
}
}
You may run it like this for UTF8:
ReadWithEncoding("D:/file.json", "UTF8");
For Cyrillic symbols:
ReadWithEncoding("D:/file.json", "Cp1251");
I too was getting this error ("Unexpected token END OF FILE at position 0.").
I was using same instance of com.google.gson.Gson and org.json.simple.parser.JSONParser on multiple threads.
Now I changed the code and created new instance of these on each thread, and that solved the issue.
gson = new GsonBuilder().create();
parser = new JSONParser();

how to read JSON from HTTP GET request?

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?
Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.
Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

Issue with i/o No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer

not sure whats going on, the full error is:
Problem with i/o No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
I am trying to send a PUT request to a RESTful service. I am parsing a POST And sending modified key/value pairs for 'ID' and 'enabled' for the PUT.
#Test(dependsOnMethods= {"Post"})
public void Put() throws IOException {
logger.logTestActivity("Testing FORM data POST using Excel file");
requestBuilder = new RequestSpecBuilder();
String jsonString = "";
boolean enabledModify = false;
try {
BufferedReader in = new BufferedReader(new FileReader(
xmlTest.getParameter("json-post")));
String str;
while ((str = in.readLine()) != null) {
jsonString += str;
}
JSONObject jsonObjPut = new JSONObject(jsonString);
jsonObjPut.put("_id", createUserId);
jsonObjPut.put("enabled",enabledModify);
System.out.println(jsonObjPut.toString());
in.close();
requestBuilder.setContentType(ContentType.JSON);
requestSpecification = requestBuilder.build();
responseBuilder.expectStatusCode(Integer.parseInt(xmlTest
.getParameter("http-status-code-200")));
responseBuilder.expectContentType(ContentType.JSON);
responseSpecification = responseBuilder.build();
System.out.println(createUserId);
String responseJson = given().body(jsonObjPut).
when().put("/" + createUserId).asString();
System.out.println(responseJson);
logger.logTestActivity("Finished testing FORM data POST using Excel file");
} catch (AssertionError e ) {
logger.logTestActivity(
"Error testing FORM data post: " + e.getMessage(),logger.ERROR);
System.out.println("REST URL: " + RestAssured.baseURI + " "
+ RestAssured.port + " " + RestAssured.basePath );
Assert.fail("Error testing FORM data POST: " + e.getMessage());
throw e;
} catch (IOException | JSONException e) {
System.out.println("Problem with i/o" + e.getMessage());
}
}
createUserID is a global variable that is the ID parsed from the POST.
JSON file that is getting parsed looks like this:
{
"enabled" : false,
"_id" : "fdse332a-22432d-4432b"
}
In a before test method I am setting up the restassured with all the appropriate url endpoints...
Also, the PUT is also failing, with a NULLPointerException Error. That may be another post in the future!
Solution: I was not converting my JSON object to a string when passing to restassured.
String responseJson = given().body(jsonObjPut.toString).
This did the trick. I now modify my existing json with generated ID and do a successful PUT on the RESTful service.
I was also facing same issue with java Spring rest Api.
It was throwing BeanSerializerExcption.
Use JsonNODE class instead of JSONObject.

Convert a JSON string to a Java/Python (Jython) object?

So I understand that you can convert JSON strings to strings and handle JSON objects in general through the org.json bundle in Android, but here's my current situation:
I need to take a JSON string from a certain URL (I'm already able to successfully do this) and make it into an array. Well actually two arrays. The framework I'm using runs on Python and returns a dict that contains lists (arrays in Python). However, it is displayed as a JSON object. Here's an example of what I would be getting from the URL to my Java code:
{"keywords": ["middle east", "syria"], "link": [["middle east", "http://www.google.com/#q=middle east"], ["syria", "http://www.google.com/#q=syria"]]}
As you can see, it's a dict of two indices. The first one is "keywords" that has a list and the second one is "link" that contains a list of lists. The two lists (the first one and the second multidimensional one) are what I want to be able to manipulate in Java. I'm aware that you can use JSONArray, but the problem is that the arrays are stored in a Python dict, and my Android application does not properly make a JSONArray. Do you guys have any ideas of how I can handle this? I'm pretty lost. Here is my code for getting the actual JSON string (the URL in the code is not accessible to everyone, it's being served by paste on my machine):
static public void refreshFeed(){
try{
String url = "http://192.17.178.116:8080/getkw?nextline="+line;
line++;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String input = null;
try {
while ((input = reader.readLine()) != null) {
sb.append(input + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String enter = sb.toString();
feedEntry add = new feedEntry(enter);
addNewEntry(add);
in.close();
} catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please also note that this is without the JSONString being made into a JSONArray. It simply translates the JSON object into a regular String that is added to a "feedEntry" object.
Mapping a python dict to a json array is ... more work than you'd expect. It'd be better to make it into either a json object or start with a list, which can be mapped straight to a json array. Info on serializing between python and java.
Here's a code example where I create a list structure in Python, and then grab it in an Android application:
#!/usr/bin/python
print "Content-type: text/html\n\n"
import json
from collections import defaultdict
mystuff = list()
mystuff.append( ('1', 'b', 'c', 'd') )
mystuff.append( ('2', 'f', 'g', 'h') )
stufflist = list()
for s in stufflist:
d = {}
d['a'] = s[0]
d['b'] = s[1]
d['c'] = s[2]
d['d'] = s[3]
stufflist.append(d)
print json.write(stufflist)
And in Android:
// Convert the string (sb is a string butter from the http response) to a json array.
JSONArray jArray = new JSONArray(sb.toString());
for(int i = 0; i < jArray.length(); i++){
// Get each item as a JSON object.
JSONObject json_data = jArray.getJSONObject(i);
// Get data from object ...
Int a = json_data.getInt("a");
String b = json_data.getString("b");
String c = json_data.getString("c");
String d = json_data.getString("d");
// Do whatever with the data ...
}

Categories