Convert serialized JSON string to JSON object in java - java

I have Json String Object as below.
"{\"SuccessData\":\"Data fetched successfully\",\"ErrorData\":\"\",\"AppData\":\"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"}"
I want to convert this string to JSON object using java.
I have already tried,
JSONObject jsonObj = new JSONObject(response);
I'm getting an error saying,
org.json.JSONException: A JSONObject text must begin with '{'

"{\"SuccessData\": \"Data fetched successfully\",
\"ErrorData\": \"\",
\"AppData\": \"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"
}"
The real problem here is that this input is not valid JSON.
Let's assume that these are the exact characters that you got in your response; i.e. the first character is a double-quote. But a valid JSON object starts with a { character. Not even whitespace is allowed according to strict reading of the syntax graph at https://json.org.
But what if that is actually a Java String literal representing the JSON?
In that case, the JSON is valid1. And what is more, your code for the JSON is correct. when I compile and run this, it works ... without throwing an exception.
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String response = "{\"SuccessData\":\"Data fetched successfully\",\"ErrorData\":\"\",\"AppData\":\"[{\\\"uniqe_id\\\":{\\\"appId\\\":4,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2223,\\\"appName\\\":ACMP\\\"},{\\\"uniqe_id\\\":{\\\"appId\\\":5,\\\"agentId\\\":1,\\\"isActive\\\":1\\\"},\\\"pid\\\":2225,\\\"appName\\\":ICMP\\\"}]\"}";
JSONObject jsonObj = new JSONObject(response);
}
}
Ergo, if you are getting a JSONException then the input is not a Java String literal.
1 - I wouldn't say it was correct. The AppData attribute has a value that is a string not a JSON object. But that string is a JSON serialization. This is technically valid, but it is a poor design choice.

I tried with the following solution and it is working,
import com.fasterxml.jackson.databind.ObjectMapper;
private JSONObject deserializeResponse(String response) {
logger.info("Parsing Serialized response object to JSON object");
JSONObject responseJson = new JSONObject();
ObjectMapper mapper = new ObjectMapper();
try {
responseJson = mapper.readValue(response.toString(),
JSONObject.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseJson;
}

Related

dynimacally generte a json object

String json = "{\"loginForm\": [{\"formType\": \"questionAndAnswer\",\"id\": 164422,\"row\": [{\"label\": \"What is the name of your state?\",\"field\": [{\"id\":\"SQandA--QUESTION_1-1\",\"value\": \""+answer1+"\"}]},{\"label\": \"What is the name of your first school\",\"field\": [{\"id\":\"SQandA--QUESTION_2-2\",\"value\": \""+answer2+"\"}]}]}],"+dataset+"}";
this json contains questions and answer in it and its hard coded in my code what should i do to dynamically generate it as i want to remove the hard code and call it dynamically.
You can create a class file with your json fields and then convert the class object to json using Jackson apis.
private String getJsonFromJava (Object obj) {
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "";
try {
jsonInString = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
System.out.println("Unable to parse object to prepare JSON string", e);
}
return jsonInString;
}
You need to write logic to create json using the inputs. If you are creating the json in JS then look at sample code below. Or you can do the same login in server side - java etc?
function createJSON() {
jsonObj = [];
$("input[questions]").each(function() {
var q= $(this).attr("Question");
var ans= $(this).val();
item = {}
item ["question"] = id;
item ["answer"] = ans;
jsonObj.push(item);
});
console.log(jsonObj);
}

While parsing a JSON, strange exception occurs as :This is not a JSON Array

I've got a broblem wih JSON parser.
Here is the JSON response from server.
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":[{"id":803,"main":"Clouds","description":"test","icon":"04d"}],
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :{"all":75},
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}
And java code ....
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
public static void main(String[] args) throws JSONException {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse("JSON responce here").getAsJsonObject();
JsonArray weather = json.get("weather").getAsJsonArray(); //no problem
int visibility = json.get("visibility").getAsInt();
int id = json.get("id").getAsInt();
int dt = json.get("dt").getAsInt();
String name = json.get("name").getAsString();
JsonArray clouds = json.get("clouds").getAsJsonArray(); //here is the problem
JsonArray main = json.get("main").getAsJsonArray(); //here is the problem
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is ... when I compile I've got java.lang.IllegalStateException: This is not a JSON Array. on JsonArray clouds = json.get("clouds").getAsJsonArray(); and others lines like this.
BUT JsonArray weather = json.get("weather").getAsJsonArray(); is OK...
I don't understand what is happening... but the array "weather" node has no problem... totally. Please, help me... what's wrong?
Because it is a Json Object
JsonObject json = json.get("clouds").getAsJsonObject()
It will work...
Or you can change the data as given below
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":{"id":803,"main":"Clouds","description":"test","icon":"04d"},
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :[{"all":75}],
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}

Java map object, which contains JSON string fields to string

I have faced problem, while mapping my object to JSON.
I have an object, which I need to convert to propper JSON, but some of my object's String fields are already in JSON format:
Sdr sdr = new Sdr();
sdr.setLocation_area(("location_area"));
sdr.setEvent_info(("{\"chargeableDur\":0}"));
sdr.setAgent_info("{\"scp\":\"NAVI\",\"stack\":\"CAP2\"}");
sdr.setService_info(("{\"bcap\":\"8090A3\",\"balID\":55969859}"));
sdr.setStarttime(("starttime"));
For JSON mapping I am using ObjectMapper:
public String toJsonString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
}
return toString();
}
However, ObjectMapper fails to map Strings, that already contains JSON correctly, and after mapping I get this type of JSON:
{
"event_info":""{\"chargeableDur\":0}",
"location_area":"location_area",
"agent_info":"{\"scp\":\"NAVI\",\"stack\":\"CAP2\"}",
"service_info":""{\"bcap\":\"8090A3\",\"balID\":55969859}",
"starttime":"starttime"
}
I want ObjectMapper to map my object like that:
{
"event_info":{
"chargeableDur":0
},
"location_area":"location_area",
"agent_info":{
"scp":"NAVI",
"stack":"CAP2"
},
"service_info":{
"bcap":"8090A3",
"balID":55969859
},
"starttime":"starttime"
}
Seems that your json result is stringified. Try to put the string result in separate JSONObject as
return new JSONObject(mapper.writeValueAsString(this)).toString();

Any method of passing the Json data in URL format using JSONObject?

I create a java URL class which contain my Json data and have some function to obtain back my json data for doing some data comparison, I found out it's might not support by JSONObject for passing the data into the JSONObject. Do I need to use JSONArray in my case because my JSON data have array structure as well?
try
{
JSONObject obj = new JSONObject ();
obj.readJsonFromUrl(theUrl);
System.out.println(obj.toString());
}
catch(MalformedURLException e)
{
System.out.print("your problem here ...1");
}
}
else
{
System.out.print("Can't Connect");
}
I am sure that this is the place give me the error message because it return me this error in my compiler
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method readJsonFromUrl(URL) is undefined for the type JSONObject
there are also some warning message for that the JSONObject readJsonFromUrl method
private static JSONObject readJsonFromUrl(URL theUrl) throws IOException, JSONException {
Anyone can provide me the explaination of how the JSON data work in java? I saw quite number of Java class for JSON which make me confuse for it such as JSONObject, JSONArray , JSONValue. I search some information online but I also not very clear about it since I am very new to JSON data processing This is my sample json data and the data I need is scan_result only
{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"file_info":{
"display_name":"",
"file_size":242,
"file_type":"Not available",
"file_type_description":"Not available",
"md5":"aa69ba384f22d0dc0551ace2fbb9ad55",
"sha1":"09ceb54e65df3d3086b222e8643acffe451a6e8a",
"sha256":"dcb46d6ae2a187f789c12f19c44bbe4b9a43bd200a3b306d5e9c1fcf811dc430",
"upload_timestamp":"2016-11-18T09:09:08.390Z"
},
"process_info":{
"blocked_reason":"",
"file_type_skipped_scan":false,
"post_processing":{
"actions_failed":"",
"actions_ran":"",
"converted_destination":"",
"converted_to":"",
"copy_move_destination":""
},
"profile":"File scan",
"progress_percentage":100,
"result":"Allowed",
"user_agent":""
},
"scan_results":{
"data_id":"a71a3c2588c6472bb4daea41a0b58835",
"progress_percentage":100,
"scan_all_result_a":"No Threat Detected",
"scan_all_result_i":0,
"scan_details":{
"Ahnlab":{
"def_time":"2016-11-08T15:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":1,
"threat_found":""
},
"Avira":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":133,
"threat_found":""
},
"ClamAV":{
"def_time":"2016-11-08T10:28:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":94,
"threat_found":""
},
"ESET":{
"def_time":"2016-11-08T00:00:00.000Z",
"location":"local",
"scan_result_i":0,
"scan_time":38,
"threat_found":""
}
},
"start_time":"2016-11-18T09:09:08.405Z",
"total_avs":4,
"total_time":250
},
"vulnerability_info":{
}
}
As mentioned here, there are many ways to solve this. Either you have to implement the read, parse operations yourself (#Roland Illig 's answer)
//you have to implement the readJSON method
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
Or you could use a library. The most well-known and widely used libraries are jackson and gson.
The big picture is that you try to "map" your json Object to a class.
You have your json file:
{
"id":1,
"name":"eirini",
"hobbies":["music","philosophy","football"]
}
and a class that represents this file and will store the values (depending on the library that you use there might be different requirements, for example getters, setters etc..)
public class Person {
public int id;
public String name;
public List<String> hobbies = new ArrayList<String>();
public String toString() {
return name +" has the id: " + id + " the following hobbies" + hobbies.get(0) + " " + hobbies.get(2);
}
}
Finally in your main method:
public static void main(String[] args) throws IOException, ParseException {
ObjectMapper mapper = new ObjectMapper();
InputStream input = this.getClass().getResourceAsStream(FILE); //read your file. There are many ways to achieve this.
ObjectMapper mapper = new ObjectMapper(); // just need one
Person eirini = mapper.readValue(input, Person.class);
System.out.println(eirini.toString());
You cannot pass json in url, you can pass it in body. Writing Json to stream body and post it using regular java method.
Here is oracle community url of explanation of your problem.
Required Jar can be downloaded from here.
Test Code Follows:
URL url = new URL("https://graph.facebook.com/search?q=java&type=post");
try (InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is)) {
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)){
System.out.print(result.getJsonObject("from").getString("name"));
System.out.print(": ");
System.out.println(result.getString("message", ""));
System.out.println("-----------");
}
}

GSON: knowing what type of object to convert to?

I'm looking into using Google's GSON for my Android project that will request JSON from my web server. The JSON returned will be either...
1) A successful response of a known type (e.g.: class "User"):
{
"id":1,
"username":"bob",
"created_at":"2011-01-31 22:46:01",
"PhoneNumbers":[
{
"type":"home",
"number":"+1-234-567-8910"
},
{
"type":"mobile",
"number":"+1-098-765-4321"
}
]
}
2.) An unsuccessful response, which will always take on the same basic structure below.
{
"error":{
"type":"Error",
"code":404,
"message":"Not Found"
}
}
I'd like GSON to convert to the correct type depending on the existence of the error key/value pair above. The most practical way I can think to do this is as follows, but I'm curious if there's a better way.
final String response = client.get("http://www.example.com/user.json?id=1");
final Gson gson = new Gson();
try {
final UserEntity user = gson.fromJson(response, UserEntity.class);
// do something with user
} catch (final JsonSyntaxException e) {
try {
final ErrorEntity error = gson.fromJson(response, ErrorEntity.class);
// do something with error
} catch (final JsonSyntaxException e) {
// handle situation where response cannot be parsed
}
}
This is really just pseudocode though, because in the first catch condition, I'm not sure how to test whether the key error exists in the JSON response. So I guess my question is twofold:
Can I / how can I use GSON to test the existence of a key, and make a decision on how to parse based upon that?
Is this what others in a similar situation are doing with GSON, or is there a better way?
What you'd normally want to do is to have your server return an actual error code along with the JSON error response. Then you read the response as an ErrorEntity if you get an error code and as a UserEntity if you get 200. Obviously this requires a little more dealing with the details of communication with the server than just turning a URL in to a String, but that's how it is.
That said, I believe another option would be to use a custom JsonDeserializer and a class that can return either a value or an error.
public class ValueOrErrorDeserializer<V> implements JsonDeserializer<ValueOrError<V>> {
public ValueOrError<V> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
JsonObject object = json.getAsJsonObject();
JsonElement error = object.get("error");
if (error != null) {
ErrorEntity entity = context.deserialize(error, ErrorEntity.class);
return ValueOrError.<V>error(entity);
} else {
Type valueType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
V value = (V) context.deserialize(json, valueType);
return ValueOrError.value(value);
}
}
}
You'd then be able to do something like this:
String response = ...
ValueOrError<UserEntity> valueOrError = gson.fromJson(response,
new TypeToken<ValueOrError<UserEntity>>(){}.getType());
if (valueOrError.isError()) {
ErrorEntity error = valueOrError.getError();
...
} else {
UserEntity user = valueOrError.getValue();
...
}
I haven't tried that code out, and I'd still recommend using the HTTP error code, but it gives you an example of how you can use a JsonDeserializer to decide what to do with some JSON.

Categories