Error on JsonElement cannot be convert to JsonObject - java

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

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);

Update Json value in json Array in 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.

Create a brand new type of searchable tree in JSON for Java

I am thinking of a new way to extract data from JSON. The following example is what I want:
Look for a key and value pair and give me that object.
Inside that object, give me the value to this key.
I want to get the power of knighthero in the following JSON, by telling it to find the username knighthero. This is really difficult, and I've tried JSONArray and JSONObject, but can't figure it out. I know the length is 3, but now what?
{
"data": [
{
"power": 75,
"registrant": {
"group": "elf",
"username": "kevin23"
}
},
{
"power": 34,
"registrant": {
"group": "fairy",
"username": "msi56"
}
},
{
"power": 150,
"registrant": {
"group": "orc",
"username": "knighthero"
}
}
]
}
I have tried JsonPath and all I get is [] when I print the string. I have tried JSONArray, but can't figure out how to do it.
With org.json librairy and your json described.
JSONObject jo0 = new JSONObject("{\"data\": ["
+ "{\"power\": 75,"
+ "\"registrant\": {\"group\": \"elf\",\"username\": \"kevin23\"}},"
+ "{\"power\": 34,"
+ "\"registrant\": {\"group\": \"fairy\",\"username\": \"msi56\"}},"
+ "{\"power\": 150,"
+ "\"registrant\": {\"group\": \"orc\",\"username\": \"knighthero\"}}"
+ "]}");
JSONArray ja = jo0.getJSONArray("data");
for(int i=0;i<ja.length();i++){
if(ja.getJSONObject(i).getJSONObject("registrant").getString("username").equals("knighthero")){
System.out.println(ja.getJSONObject(i).getInt("power"));
break;
}
}
EDIT
My bad, I make a mistake, here the good version

Android: org.json.JSON.typeMismatch

I've got a method below, which is parsing JSON. However I've run into an error (which you can see from the title), where it is saying "org.json.JSON.typeMismatch" .
Trying to log the names that are getting output however having no luck. I've little experience with cracking JSON (as you can probably tell from this), so wondering how to go about fixing this issue.
private Boolean parse()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo;
realms.clear();
for (int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name = jo.getString("name");
Log.d("",name);
//realms.add(name);
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
And the JSON I am trying to parse into here is:
{
"realms": [{
"type": "pvp",
"population": "low",
"queue": false,
"status": true,
"name": "Aegwynn",
"slug": "aegwynn",
"battlegroup": "Misery",
"locale": "de_DE",
"timezone": "Europe/Paris",
"connected_realms": ["aegwynn"]
}, {
"type": "pve",
"population": "low",
"queue": false,
"status": true,
"name": "Aerie Peak",
"slug": "aerie-peak",
"battlegroup": "Reckoning / Abrechnung",
"locale": "en_GB",
"timezone": "Europe/Paris",
"connected_realms": ["bronzebeard", "aerie-peak"]
}]
(there is more to this but I'd rather not copy it all)
Not sure if perhaps I'm not addressing the "realms" array? Just would appreciate any help on this! As I can't see quite why I'm getting a mismatch?
Kind Regards
J G
Your JSON string show up here it is a JSONObject not a JSONArray, so that you must init an JSONObject with this string, after that get a JSONArray with name realms from previous JSONObject. Here is an example for your reference

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Categories