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

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?

Related

Getting error when trying parse JSON string. org.json.JSONException: A JSONArray text must start with '['

I am trying to parse a JSON string so I could turn it into an array and iterate through each element through indexing.
Below is my code:
String body = "{\"user\":\"d26d0op3-7da5-6ad8\",\"pass\":\"12784949-2b8c-827d\"}";
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(body);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
System.out.println(stringArray);
When I run this code, I get the following error:
Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
I tried formatting my body differently with:
String body = "[{\"user\":\"d26d0op3-7da5-6ad8\",\"instanceId\":\"12784949-2b8c-827d\"}]";
But then I got the following error:
Exception in thread "main" org.json.JSONException: JSONArray[0] is not a String.
How would I go about correctly parsing my JSON?
You might want to read up a bit on the JSON format. Try http://json.org .
In your first case, body is a JSON 'object', not an array. This is similar to a dictionary, or key:value pair map. A JSON object is delimited with { and }.
To parse this body, you would use:
JSONObject job = new JSONObject(body);
String username = job.getString("user");
I think that is probably what you are after.
In the second case, your body is a JSON array that contains one JSON Object. A JSON array is delimited by [ and ]
If you want a JSON array of strings, it would look something like this, instead:
body = "[ \"a\", \"b\", \"c\" ]";
An array of integers would look like:
body = "[ 1,2,3,4 ]";
You can use the ObjectMapper.readValue(String, Class<T>) method to parse a value from a json string to some object. In this case it can be a Map<String, String>:
String body = "{\"user\":\"d26d0op3-6ad8\",\"pass\":\"12784949-827d\"}";
Map<String, String> map = new ObjectMapper().readValue(body, Map.class);
System.out.println(map); // {user=d26d0op3-6ad8, pass=12784949-827d}
If you are expecting a list of some objects:
String body = "[{\"user\":\"d26d0op3-6ad8\",\"pass\":\"12784949-827d\"}]";
List<Object> list = new ObjectMapper().readValue(body, List.class);
System.out.println(list); // [{user=d26d0op3-6ad8, pass=12784949-827d}]
The String body = "{"user":"d26d0op3-6ad8","pass":"12784949-827d"}" is not a array
enter image description here
you can convert to json array like this
String body = "[{"user":"d26d0op3-7da5-6ad8","pass":"12784949-2b8c-827d"}]";

Can't parse Java JSON string

From my server is get a JSON response like this:
String json = getJsonFromServer();
The server returns this reply (with the double quotes in the beginning and end):
"{\"error\":\"Not all required fields have been filled out\"}";
I then want to get the error field. I have tried to use the JSONObject class to get the string, but it does not work.
System.out.println("The error is: " + new JSONObject().getJSONObject(response).getString("error");
I have try
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(response);
System.out.println(json.get("error").toString());
} catch (ParseException ex) {
}
It have working, you can try it and don't forget add json lib json-simple
You seem to be using the wrong JSONObject constructor; in your example, you are trying to fetch an object from a newlay created object - it will never exist.
Try this:
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject json = new JSONObject( response );
String error = json.getString( "error" );
System.out.println( error );
Yields
Not all required fields have been filled out
edit
Now that you have completely changed the question...
Why not just first strip the first and last char?
So if
String response = "\"{\"error\":\"Not all required fields have been filled out\"}\"";
response = response.substring(1, response.length() - 1));
// Now convert to JSONObject
Your response object has exactly this string?
{"error":"Not all required fields have been filled out"}
The code below printed the expected output:
Object responseObject = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject jsonObject = new JSONObject(responseObject.toString());
String errorContent = jsonObject.getString("error");
System.out.println(errorContent);

Error while parsing JSON in 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

Remove back slash from Json String in android

i need some help for Remove Back slash from Json String.
Here is the Response which i Get From Server side.
"response":"{\"time_zone\":\"\",\"session_token\":\"abcdefgHijklomopqrstuvwxyz\",\"user_login\":\"abc\",\"user_profile_img\":\"http://jhjhjhj.org/system/photos/62/medium/images.jpg?1462446436\",\"success\":\"0\",\"org_admin\":\"\",\"user_id\":\"62\",\"user_org_id\":\"101\",\"phone_mobile\":\"510-427-9639\",\"user_email\":\"abc#pdmoffice.com\"}"}
what i have don for Remove Backslash from this String
result.replaceAll("\\","");
than After it will give me This String which is not in Json Formate.
{"response":"{"time_zone":"","session_token":"nskfndkjfsfsdffjsdfd","user_login":"newoff2","user_profile_img":"http://absdds.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9639","user_email":"hjhjh#pdmoffice.com"}"}
it Give me Exaption
org.json.JSONException: Unterminated object at character 17 of
{"response":"{"time_zone":"","session_token":"kjshhdscncnxzcxclx","user_login":"newoff2","user_profile_img":"http://abcd.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9898","user_email":"sdgas#pdmoffice.com"}"}
How Can i remove this Back slash with Proper Json Formate ?
Thanks in advance
The command
result.replaceAll("\\","");
is correct and if you try to display the server response with an online json formatter (https://jsonformatter.curiousconcept.com/) you can clearly see that the string is not correctly formatted. The double quotes after the "response" and one at the end are not required.
UPDATED: August 2019
Use google's Gson for parsing to Json by omitting backslash automatically:
JAVA CODE:
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse("your jsonString with backslash").getAsJsonObject();
KOTLIN CODE:
val jsonParser = JsonParser()
val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject
An alternative to remove backslashes from JSON string.
s = Your String with Back Slash
For converting String to JSONObject:
JSONObject jsonObject = new JSONObject(s);
For converting String to JSONArray:
JSONArray jsonArray = new JSONArray(s);
You can try this and it will work fine
String jsonStr4 = jsonStr3.replaceAll("\"", "");

Converting json string to JSONArray in java?

I have this json string returned from a 3rd party api
{"msg":"xff","uuid":"44037b67-3629-4325-83e5-7a00cb78dfdf"}
When I try to parse it by the below code
JSONArray json = new JSONArray(message.toString());
JSONArray arr = json.getJSONArray(0);
String mess = arr.getJSONObject(0).getString("msg");
String uuid = arr.getJSONObject(0).getString("uuid");
System.out.println("message : "+mess);
System.out.println("uuid : "+uuid);
I get this below exception
org.json.JSONException: Value {"msg":"xff","uuid":"44037b67-3629-4325-83e5-7a00cb78dfdf"} of type org.json.JSONObject cannot be converted to JSONArray
What other way can I parse it?
You can use JSONObject instead:
JSONObject obj = new JSONObject(message);
String mess = obj.getString("msg");
String uuid = obj.getString("uuid");
System.out.println("message : "+mess);
System.out.println("uuid : "+uuid);

Categories

Resources