I have the following String passed to server:
{
"productId": "",
"sellPrice": "",
"buyPrice": "",
"quantity": "",
"bodies": [
{
"productId": "1",
"sellPrice": "5",
"buyPrice": "2",
"quantity": "5"
},
{
"productId": "2",
"sellPrice": "3",
"buyPrice": "1",
"quantity": "1"
}
]
}
which is a valid json for http://jsonlint.com/
I want to get the bodies array field.
That's how I'm doing it:
Gson gson = new Gson();
JsonObject object = gson.toJsonTree(value).getAsJsonObject();
JsonArray jsonBodies = object.get("bodies").getAsJsonArray();
But on the second line I'm getting exception listed below:
HTTP Status 500 - Not a JSON Object: "{\"productId\":\"\",\"sellPrice\":\"\",\"buyPrice\":\"\",\"quantity\":\"\",\"bodies\":[{\"productId\":\"1\",\"sellPrice\":\"5\",\"buyPrice\":\"2\",\"quantity\":\"5\"},{\"productId\":\"2\",\"sellPrice\":\"3\",\"buyPrice\":\"1\",\"quantity\":\"1\"}]}"
How to do it properly then ?
Gson#toJsonTree javadoc states
This method serializes the specified object into its equivalent
representation as a tree of JsonElements.
That is, it basically does
String jsonRepresentation = gson.toJson(someString);
JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class);
A Java String is converted to a JSON String, ie. a JsonPrimitive, not a JsonObject. In other words, toJsonTree is interpreting the content of the String value you passed as a JSON string, not a JSON object.
You should use
JsonObject object = gson.fromJson(value, JsonObject.class);
directly, to convert your String to a JsonObject.
I have used the parse method as described in https://stackoverflow.com/a/15116323/2044733 before and it's worked.
The actual code would look like
JsonParser jsonParser = new JsonParser();
jsonParser.parse(json).getAsJsonObject();
From the docs it looks like you're running into the error described where your it thinks your toJsonTree object is not the correct type.
The above code is equivalent to
JsonElement jelem = gson.fromJson(json, JsonElement.class);
as mentioned in another answer here and on the linked thread.
What about JsonArray jsonBodies = object.getAsJsonArray("bodies");
Related
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);
{
"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.
I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar
Assignment: I am using json-simple. How can I convert this json data into individual java strings?
(Please forgive me if you think that this is a low-level question - I am new to JSON, so I don't know much about that - I've searched a lot, but I couldn't find any answers)
I can get the data if there is only one object ... like this ...
{
"name": "Abhi",
"age": "21"
}
But, I can't get the data if it is in the array
[{
"name": "Abhi",
"age": "21"
}, {
"name": "shek",
"age": "7"
}]
my program logic for json object
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("A:/c/dataFile.json"));
JSONObject jObj = (JSONObject) obj;
String gName = (String) jObj.get("name");
String gAge = (String) jObj.get("age");
System.out.println(gName);
System.out.println(gAge);
Can anyone show me how to get the data? maybe a code snippet?
Thanks in advance for your answer!
Because in your second case you are getting JSONArray
you may need to check the instance of obj as
if (jObj instanceof JSONObject)
else if (jObj instanceof JSONArray)
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