Update Json value in json Array in Java - java

{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}

The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.

That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.

Related

Can't deserialize JSON array into class org

I want to make a string from json into an object of my class. The problem is, in the class I use an ArrayList and that's why (I think) I get the error message "Can't deserialize JSON array into class". How exactly can I separate the array and convert it into an ArrayList?
#POST
public Response createMocktail(String m){
MocktailDto mocktail = jsonb.fromJson(m, MocktailDto.class);
return Response.ok(mocktailManager.createMocktail(mocktail)).build();
}
Json String:
[
{
"id": 3,
"name": "Mojito",
"zutaten": [
{
"anzahl": 1,
"id": 5,
"name": "Rum"
},
{
"anzahl": 1,
"id": 6,
"name": "GingerAle"
}
]
}
]
JSONObject jsonObj = new JSONObject(m); does not work, it says constructor is undefined although I saw a few solutions like this
The problem is your input string is Array (when it starts with [)
There are a few possible solutions:
First:
MocktailDto[] data = jsonb.fromJson(m, MocktailDto[].class);
data[0];
Second:
Type listType = new TypeToken<ArrayList<MocktailDto>>(){}.getType();
ArrayList<MocktailDto> data = jsonb.fromJson(m, listType);
data.get(0);

Error on JsonElement cannot be convert to JsonObject

so there is a jsonReqObj,
jsonReqObj = {
"postData" : {
"name":"abc",
"age": 3,
"details": {
"eyeColor":"green",
"height": "172cm",
"weight": "124lb",
}
}
}
And there is a save function that will return a string. I want to use that save function, but the input parameter for the save json should be the json inside postData.
public String save(JsonObject jsonReqObj) throw IOException {
...
return message
}
below are my code
JsonObject jsonReqPostData = jsonReqObj.get("postData")
String finalMes = save(jsonReqPostData);
But I am getting the error that
com.google.gson.JsonElement cannot be convert to com.google.gson.JsonObject.
JsonObject.get returns a JsonElement - it might be a string, or a Boolean value etc.
On option is to still call get, but cast to JsonObject:
JsonObject jsonReqPostData = (JsonObject) jsonReqObj.get("postData");
This will fail with an exception if it turns out that postData is a string etc. That's probably fine. It will return null if jsonReqObj doesn't contain a postData property at all - the cast will succeed in that case, leaving the variable jsonReqPostData with a null value.
An alternative option which is probably clearer is to call getAsJsonObject instead:
JsonObject jsonReqPostData = jsonReqObj.getAsJsonObject("postData");
I have validated your JSON file with https://jsonlint.com/ and it looks like the format is incorrect, instead of be:
jsonReqObj = {
"postData": {
"name": "abc",
"age": 3,
"details": {
"eyeColor": "green",
"height": "172cm",
"weight": "124lb",
}
}
}
Should be:
{
"postData": {
"name": "abc",
"age": 3,
"details": {
"eyeColor": "green",
"height": "172cm",
"weight": "124lb"
}
}
}
Maybe thats why you cant convert to an object
Note: I would put this as a comment instead as an answer, but i dont have enought reputation T_T

Get all records from JSON response

I'm still kind of new to the Rest Assured API world. I've read through as much documentation on https://github.com/rest-assured/rest-assured/wiki/Usage#example-3---complex-parsing-and-validation as I can stand.
I have a response that looks like:
{
"StatusCode": 200,
"Result": [
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "Home",
"PhoneNumber": "9701234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile1",
"PhoneNumber": "2531234567",
},
{
"EmployeeId": "5661631",
"PhoneTypeDescription": "mobile2",
"PhoneNumber": "8081234567",
}
]
}
I've been struggling with how to get just the first record's PhoneNumber.
String responseBody=
given()
.relaxedHTTPSValidation().contentType("application/json")
.param("api_key", api_key).
when()
.get("/api/employees/" + employeeId)
.andReturn().asString();
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result");
phoneNumber = jsonPath.getString("PhoneNumber");
I get all the phone numbers in this case:
phoneNumber = "[9701234567,2531234567,8081234567]"
How can I get just the first record? I'd rather not have to perform string operations to deal with the, "[".
Thanks
You can simply do,
JSONObject json = new JSONObject(responseBody);
phoneNumber = json.getJSONArray("Result").getJSONObject(0).getString("PhoneNumber");
Here, 0 indicates the first record in the JSON Array Result.
Because you know the index of the element you want to retrieve, you can use the following code:
JsonPath jsonPath = new JsonPath(response);
String phoneNumber = jsonPath.getString("Result[0].PhoneNumber");

Converting Nested Json files to CSV in java

{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}

Different JSON array response

I have problems parsing two different JSON responses.
1: This is the JSON response I get from a RESTful API:
{
"gear": [
{
"idGear": "1",
"name": "Nosilec za kolesa",
"year": "2005",
"price": "777.0"
}, {
"idGear": "2",
"name": "Stresni nosilci",
"year": "1983",
"price": "40.0"
}
]
}
2: This response I get from my testing client. I was added some values to the list and then I used gson.toJson for testing output.
[
{
"idGear": "1",
"name": "lala",
"year": 2000,
"price": 15.0
}, {
"idGear": "2",
"name": "lala2",
"year": 2000,
"price": 125.0
}
]
They are both valid, but the second one was successfully deserialize to object like this:
Type listType = new TypeToken<List<Gear>>() {}.getType();
List<Gear> gears= (List<Gear>) gson.fromJson(json, listType);
With the first one, I was trying to deserialize the same way but I get error.
EDIT
API Method:
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Gear> getGear() {
List<Gear> gears = gearDAO.getGears();
if (!gears.isEmpty()) {
return gears;
} else
throw new RuntimeException("No gears");
}
CLIENT serialization code:
List<Gear> list = new ArrayList<Gear>();
Gear o = new Gear();
o.setPrice(15);
o.setYear(2000);
o.setName("asds");
Type listTypes = new TypeToken<List<Gear>>() {}.getType();
gson.toJson(list, listTypes);
The JSON responses are different!
The first one is an object, surrounded by { }, which contains a field "gear" that is in turn a list of objects, surrounded by [ ].
The second one is directly a list of objects, because it's surrounded by [ ]. Namely, the whole 2nd response is equivalent to the field in the 1st response.
So, obviously they can't be parsed in the same way...
The 2nd one is being parsed correctly because you are using a List and it is a list. But for the 1st one you need another class that contains a field that contains in turn a list... That is, you just need to create a class structure that represents your JSON responses...
public class Response {
private List<Gear> gears;
//getters & setters
}
Now you can parse your 1st response with:
Gson gson = new Gson();
Response response = gson.fromJson(json, Response .class);
List<Gear> gears = response.getGears();
I suggest you to take a brief look at json.org in order to understand JSON syntax, which is pretty simple...
Basically these are the possible JSON elements:
object
{}
{ members }
members
pair
pair , members
pair
string : value
array
[]
[ elements ]
elements
value
value , elements
value
string
number
object
array
true
false
null

Categories