Error while parsing JSON in Java - java

I am creating JSON using JavaScript as:
var myJson = '{'
+ '"name" : "myname",'
+ '"gender" :"' + gender
+ '"}';
However, while parsing it in Java using:
JSONParser jParser = new JSONParser();
JSONObject jObj = (JSONObject) jParser.parse(myjson);
I am getting below error:
(java.lang.ClassCastException) java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject

by using a library, you can do it directly like this:
JSONObject obj = new JSONObject(stringValue);
you can then iterate over the object.
https://github.com/stleary/JSON-java and for more details you can have a look at Parsing JSON Object in Java

Related

Can't use (google.gson) jsonParser to parse string as jsonObject

I want to parse my string input as a json and then get items from it for this reason i have added this code:
String data=new String(content.getBytes(),"UTF-8");
String x=data.replaceAll("[\\n\\r\\t]+", "");
System.out.println(x+"=================================================");
FormatedData="id:"+id+"\n"+"name:"+name+"\n"+"comment:"+comment;
String id,name,comment;
JsonParser parser = new JsonParser();
System.out.println(x+"===================================================");
JsonObject obj = (JsonObject) parser.parse(x).getAsJsonObject();
System.out.println(obj+"===============================================");
name = obj.get("organizationNameEN").getAsString();
id = obj.get("id").getAsString();
comment=obj.get("comment").getAsString();
String FormatedData="id:"+id+"\n"+"name:"+name+"\n"+"comment:"+comment;
here is my JsonData:
{id:15, organizationNameGE:55, organizationNameEN:5656, cardNumber:6767, startDate:02/04/2018, period:5, endDate:02/10/2018, priority:not so important, $$hashKey:19A, comment:comment, mail:mail}
I am useing this library for parsing com.google.gson.JsonParser; but when i try to make this operation i got this error:
com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 89 path $.startDate
I HVAE REMOVED ALL SPACES FROM STRING WHAT SHOULD I CHENAGE HERE TO GET RID OF THIS ERROR?

Converting json object to json array using org.json.simple

I have one org.json.simple.JSONObject i.e {"2016":
obj = {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}
I want to convert to json array like
org.json.simple.JSONArray arr = obj.toJsonArray(obj); //no such method exists
Is there any method available to convert above object to array.
or do i need to iterate to make it JSONArray.
I am using org.json.simple not org.json.
The String is a JSONObject not JSONArray.
String s = {"12":{"19":{"12":"{\"DonationTime\":11111111111,\"Donation\":10}"}}}}
You can use the following code:
Object obj = parser.parse(s);
JSONObject object = (JSONObject)obj;
Creating JSONArray:
JSONArray list = new JSONArray();
list.add(object);

What is wrong with my JSON string?

I think the JSON string I had was working fine. I stumbled across on my unit tests and found out that my JSON parsing using google Gson library doesn't work anymore. Does anybody have any ideas why this is not working?
String json = "{\"hybrid\":\"true\",\"trimName\":\"act\"}";
JsonObject data = new Gson().fromJson(json, JsonObject.class);
System.out.println(" JSON is "+data);
System.out.println(" JSON is "+data.get("hybrid"));
The output I get is
JSON is {}
is hybrid ? null
Solution 1
Solution in JsonObject as well using JsonParser to convert JSON string directly into JsonObject without using Gson.
JsonParser parser = new JsonParser();
JsonObject jsonObject = (JsonObject) parser.parse(json);
System.out.println(" JSON is " + jsonObject);
System.out.println(" JSON is " + jsonObject.get("hybrid"));
output:
JSON is {"hybrid":"true","trimName":"act"}
JSON is "true"
Solution 2
You can convert JSON string into Map<String, String> using TypeToken and Type
String json = "{\"hybrid\":\"true\",\"trimName\":\"act\"}";
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> data = new Gson().fromJson(json, type);
System.out.println(" JSON is " + data);
System.out.println(" JSON is " + data.get("hybrid"));
output:
JSON is {hybrid=true, trimName=act}
JSON is true

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

Parsing String to JsonObject using GSON gives IllegalStateException: This is not a JSON Object

I have the following code:
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
It's because due to the JSON structure..
I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
This should give you some basic idea.
ArrayList<String> roomTypes = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for(int i =0; i<jsonArray.length(); i++){
roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}
The problem with the code is that roomList is not a JsonObject as evident in the printed output. It's actually a JsonArray.
To fix the code, call .getAsJsonArray() (instead of .getAsJsonObject())
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);

Categories

Resources