How to parse Javascript JSON array into ArrayList from Servlet - java

I have an Angular JS function that sends a JSON array to a Java Servlet. With GSON class I am trying to parse that array back into an ArrayList of String (or another Class later). Unfortunately it looks like the ArrayList I get is null. Any suggestion?
EDIT: I forgot about request.getReader(), it works now.
Payload Sent:
{"answers":["answer1","answer2"]}
Angular JS Code:
$scope.test = function() {
var answers = [];
answers.push('answer1');
answers.push('answer2');
$http({
method: 'POST',
url: '/test',
data: { answers: answers }
}).success(function(result) {
// RESULT IS NULL
}).error(function(result) {
});
};
Java Servlet Code:
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(request.getReader(), JsonElement.class);
JsonObject jsonObject = jsonElement.getAsJsonObject();
ArrayList<String> answers = gson.fromJson(jsonObject.get("answers").getAsJsonArray(), new TypeToken<ArrayList<String>>(){}.getType());

You cannot use request.getParameter to get the JSON message that you pass from Angular. Instead you have to use request.getReader
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(request.getReader());
Now JsonObject will have the message you sent. Now you can use this obj to convert it to an Array List.
Also in your Angular $http post, set the data to answers like this:
$http({
method: 'POST',
url: '/test',
data: JSON.stringify(answers)
}).success(function(result) {
// RESULT IS NULL
After you have the JsonObject, you can use this to convert it into an ArrayList
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}

Related

Passing Array as a BODY in a POST request

I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's.
I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.
The code I have been using for json object is
obj = parser.parse(new FileReader("path of json"));
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
This code gives class cast exception at
jsonObject = (JSONObject) obj; when I pass a json array.
Kindly help me with the same
This is the JSON Array
[
{
"findingId": "20177044",
"unsupressAfterDuration": 1669968369043,
"developer": "manan.girdhar#armorcode.io",
"kbIds": [],
"ticketConfigurationId": "3350",
"customFields": []
}
]
Your parser parses the part of JSON and probably returns a JSONArray, but you are casting it to JSONObject. Maybe you want to use something like
obj = parser.parse(new FileReader("path of json"));
if (obj instanceof JSONObject) {
jsonObject = (JSONObject) obj;
String jsonString = jsonObject.toJSONString();
Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
response = RestAssuredExtension.PostOpsWithBody(url, body);
} else {
throw new Exception("We do not know how to handle non-objects like " + obj.getClass().getName());
// replace this with list-handling code
}
If you want only one code fragment to handle both objects and lists, cast to JsonStructure.
answering my own question as I found a solution
JSONArray array1 = new JSONArray();
data1.put("findingId", findingIdFinal);
data1.put("unsupressAfterDuration", "1669968369043");
data1.put("developer","manan.girdhar#armorcode.io");
data1.put("kbIds",array1);
data1.put("ticketConfigurationId", jiraId);
data1.put("customFields",array1);
array.put(data1);
String jsonString = array.toString();
List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);
response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);

Find JSON object in JSON array

I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.

JSONObject from Google Maps parse in Java

I'm trying to parse Java Object to get data from a URL. I'm using getJSONObject and getString methods from org.json.JSONObject library but this it's not working. I'm doing something like...
JSONObject jsonCoord = json.getJSONObject("results")
.getJSONObject("geometry")
.getJSONObject("location");
coordinates[0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
JSON document I want to parse (Part 1)
JSON document I want to parse (Part 2)
How can I get "lat" and "lng" which is inside of "geometry"?
Here it is:
public static void main(String args[]) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("test.json")), "UTF-8");
JSONObject json = new JSONObject(content);
JSONArray results = json.getJSONArray("results");
JSONObject result = (JSONObject) results.get(0); //or iterate if you need for each
JSONObject jsonCoord = result.getJSONObject("geometry").getJSONObject("location");
System.out.println(jsonCoord);
String[] coordinates = new String[2];
coordinates [0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
System.out.println(Arrays.asList(coordinates));
}

Json Iterating using java

Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.

parsing URL in String from JSON

1) I've got a JSON file:
{
"serverURI":"http://localhost:8080/PocketUNI_API/serverURLs",
"newsURI":"http://localhost:8080/gateway/rss/rss.xml",
"modulesURI":"http://localhost:8080/PocketUNI_API/modules"
}
2) I need to get URLs on Java client in String format.
String json = jsonReceiver.makeHttpRequest(URL_SERVER, "GET", params);
JSONArray uris = new JSONArray(json);
Receiver works fine and json shows the correct string received, but when it goes to parsing with JSONArray it throws an error
org.json.JSONException: Value {"serverURI":"http:\/\/192.168.0.... of type org.json.JSONObject cannot be converted to JSONArray.
Question: How to parse json with URL values?
You don't get a JSONArray but a JSONObject.
JSONObject uris = new JSONObject(json);
json is a json object not an array, that is why you are getting the error. An array will be wrapped with in [ and ], and objects within { and }.
JSONObject uris = new JSONObject (json);
Instead of JSONArray you must use JSONObject.
JSONObject uris = new JSONObject(json);
In your code just replace JSONArray to JSONobject
JSONObject uris = new JSONObject(json);

Categories

Resources