I have the following code:
try {
JSONObject json = new JSONObject(data);
...
} catch(JSONException ex) {
if(LOGS_ON) Log.e(TAG, "Could not save data.", ex);
}
It throws an exception, although the json string passed in is pretty valid. The exception is the following:
org.json.JSONException: Value {"ShopId3Digit":"ww0","ServerTime":1426695017191,"SMSTelephone":"2104851130","SendPODAgain":true,"SendLocationAgain":true,"IsHUB":false,"AllowReceiptsAndDeliveries":true} of type java.lang.String cannot be converted to JSONObject
Do you see something wrong with the json data I'm passing in?
BTW this is the string as seen in Eclipse watch:
"{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}"
Here's a working version
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
String data = "{\"ShopId3Digit\":\"ww0\",\"ServerTime\":1426695017191,\"SMSTelephone\":\"2104851130\",\"SendPODAgain\":true,\"SendLocationAgain\":true,\"IsHUB\":false,\"AllowReceiptsAndDeliveries\":true}";
try {
JSONObject json = new JSONObject(data);
System.out.println("Success: json = ");
System.out.println(json.toString(2));
} catch(JSONException ex) {
System.out.println("Error: " + ex);
}
}
}
(using the most recent version available at https://github.com/douglascrockford/JSON-java). I have tested this code, it compiles and successfully outputs
Success: json =
{
"IsHUB": false,
"SMSTelephone": "2104851130",
"AllowReceiptsAndDeliveries": true,
"SendPODAgain": true,
"SendLocationAgain": true,
"ShopId3Digit": "ww0",
"ServerTime": 1426695017191
}
Therefore, the error seems to be not with the json data.
It was my mistake after all. I obtain the data from a .NET program through Newtonsoft serializer. By mistake I was serializing the already serialized object resulting in just a string. The starting and ending quotes in the watch in Eclipse are actually part of the value.
Thank you godfatherofpolka for the effort you went through.
Related
I would like to make sure o is a serializable top level JSON object, that is [] or {} else throw an exception. I have tried the following code using "" and null as input but they are not triggering an exception.
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
try{
Gson gson = new Gson();
gson.toJson(o);
} catch (Exception e) {
throw new MissingRequiredValueException(message);
}
}
What would need to change to get the check I want?
Update:
After comments it clear my understanding was wrong. My question has change to:
How can I assert only [] and {} are valid in the following function?
As others have mentioned, modern definitions of JSON do allow primitives (strings, numbers, booleans, null) as top-level elements. But if you really need to do this check with GSON, here's one option:
private static final Gson gson = new Gson();
static void checkIsjsonSerializable(Object o, String message)
throws MissingRequiredValueException {
JsonElement rootElement = gson.toJsonTree(o);
if (!rootElement.isJsonArray() && !rootElement.isJsonObject()) {
throw new MissingRequiredValueException(message);
}
}
I am having some trouble with converting a Set of POJO's to a JSON string so I can store it in a database column. The conversion to JSON works as expected but when the conversion from JSON to a Set< Qualification > happens it always returns a LinkedHashSet<LinkedHashMap> which is causing issues.
The weird thing is that inside my converter the JSON string is converted successfully to a Set<Qualification>. When I debug in my IDE and step through the execution I can see that after it calls a deepCopy method in the MutableMutabilityPlan abstract class. At this point the data is of type LinkedHashSet<LinkedHashMap> and not Set<Qualification> from the conversion.
Here is my converter.
public class SetToStringConverter implements AttributeConverter<Set<Qualification>, String> {
private final ObjectMapper mapper = new ObjectMapper();
private final String errorMessage = "converter.invalid";
#Override
public String convertToDatabaseColumn(final Set<Qualification> items) {
try {
return mapper.writeValueAsString(items);
} catch (JsonProcessingException e) {
throw new ConverterFailureException(errorMessage);
}
}
#Override
public Set<Qualification> convertToEntityAttribute(final String data) {
try {
if (data != null) {
final Set<Qualification> s = mapper.readValue(data, new TypeReference<Set<Qualification>>() {});
return s; // Debugging here I have the correct type
}
return new HashSet<>();
} catch (IOException e) {
throw new ConverterFailureException(errorMessage);
}
}
}
I have done some research and have tried various approaches but the result is always the same.
Has anyone run into this issue before or can see anything wrong with my converter. Let me know if anything isn't clear so I can provide more information.
Thanks very much for the help.
I am trying to parse my JSONObject to get my JSON Array's data.
But the problem is JSONParser is a class in org.json.simple.JSONParser and the JSONObject is in org.json.JSONObject.
I cannot find any parser in org.json to avoid class cast exception!
Do we have any other way to get this stuff sorted...?
Or am i going in a completely wrong direction?
Please suggest
My JSON looks like :
{
"dataIntents": [
{
"intent": "muster.policy.daily",
"expr": "Am I supposed to register my attendance daily?"
},
{
"intent": "leave.probation",
"expr": "An employee is eligible for how many leaves in 1st year ??"
},
{
"intent": " leave.resigned ",
"expr": "Are resigned employees eligible for pro rata leave credit"
},
{
"intent": " muster.deadline.submission ",
"expr": "By when should I get my pending leave/Emuster applications
approved?"
}
]
}
My main class:
public class DLMain {
public static void main(String[] args) {
try {
JSONParser parser = new JSONParser();
Object obj =
parser.parse(newFileReader("/home/cmss/Downloads/data.json"));
org.json.JSONObject dataObject = (org.json.JSONObject)obj;
System.out.println(dataObject);
org.json.JSONArray getArray =
dataObject.getJSONArray("dataIntents");
for (int i = 0; i < getArray.length(); i++) {
org.json.JSONObject objects = getArray.getJSONObject(i);
String a = objects.getString("expr");
}
System.out.println();
} catch (Exception e) {
System.out.println(e);
}
}
}
I want all values of my "expr" key in a JSONObject or String.
Help appreciated in advance :)
Why don't you use a POJO for that?
So far your Json is a list of intents, you can have something like:
public class Intents {
private List<Intent> dataIntents;
}
and another
public class Intent {
private String intent;
private String expr;
}
(please generate the constructor and getter setter)
And then you can use directly the ObjectMapper and you avoid all the ugly JSON parsing.
Hope it helps!
I'm getting many JSON objects through a web service and at times the json object is malformed.
I wanted to check the if the json is valid before processing it.
So i worte
JsonElement jsonData = parser.parse(attacheddataattribute);
if(jsonData.isJsonObject())
{
//then only process
}
Not also its throwing a
com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 8432 at the parse method.
Is there any implemenation available to check for the JSON's validity.
That's your validation. No need to call any service.
If the method is throwing the MalformedJsonException it's a malformed JSON.
If you want you can wrap it in a method like
public boolean isValidJson(String json) {
try {
// parse json
return true;
} catch(MalformedJsonException e) {
return false;
}
}
I also had the MalformedJsonException crash but in my case I needed to add a catch block with Throwable:
fun jsonToList(value: String?): MutableList<String> {
var objects: Array<String> = emptyArray()
try {
objects = Gson().fromJson(value, Array<String>::class.java)
}catch (t: Throwable){
}finally {
return objects.toMutableList()
}
}
very simple java/json question.
I have the following test chunk of code. I can get the 1st element using the ".get()" by either index, or by the key. but I can't get any other elements by key...
The test dies, with nothing on the cmdline.. I'm assuming this is due to something not being correctly set within my env to display err results..
UPDATE::
OK.. it appears that the real issue is I don't know how to get an item, and to 1st determine what "type" it should be cast to. for the "nickname","name".. if I cast them as String.. I get the correct result..
So, how can one iterate through the key/value list of the json to determime how to correctly get each item??
The test code is:
import org.json.simple.JSONObject;
import org.json.simple.*;
//import org.json.simple.JSONValue;
public class asuH {
public static void main(String[] args){
final String[] arguments = args;
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try{
String json_=arguments[0];
//--get the page for the 1st and 2nd urls...
//test the json input..
System.out.println("asdfsfd \n");
System.out.println(json_);
//JSONObject obj=new JSONObject();
//Object obj=JSONValue.parse(json_);
String k9="{\"nickname\":null,\"num\":100,\"contact\":{\"phone\":\"123456\",\"zip\":\"7890\"},\"balance\":1000.21,\"is_vip\":true,\"name\":\"foo\"}";
//JSONObject obj = (JSONObject)JSONValue.parse(json_);
JSONObject obj = (JSONObject)JSONValue.parse(k9);
System.out.print("11 \n");
String fa = (String)obj.get("nickname");
System.out.print(fa);
System.out.print("22 \n");
fa = (String)obj.get("contact"); //<< not working!!!
System.out.println("22 cc\n");
System.out.println(fa);
String ttt=obj.toString();
System.out.print(ttt);
System.out.println("\n s4354455 \n");
System.exit(0);
}
catch (Exception ex) {}
System.exit(0);
}
});
}
}
any thoughts/pointers are appreciated.
thanks
The value corresponding to property named contact is not a String. Use the appropriate getter method, and don't cast.
// snip...
String fa = obj.getString("nickname");
// snip...
JsonObject contact = obj.getObject("contact");
// and so on
You can get field from your object and ask for it's type:
Object field = obj.get("field");
if (field instanceof JSONArray) {
...
} else if (field instanceof JSONObject) {
...
} else if (field instanceof Number) {
...
} else {
...
}
You get the picture...