I am stuck in a situation, where my JSONString (ruleFormJSONString) looks like :
{
"ruleDescription":"Test Rule2 Description",
"urlId":"1",
"listOfBusinessdays":["1","2","5","6","7"],
"status":"1",
"hierarchyId":"3",
"fromTime":"08:00",
"toTime":"18:00",
"dcnid":"1",
"eventId":"1",
"rowstate":"1",
"listOfLocations":["ASM","DEL"],
"ruleName":"Test Rule2",
"ruleId":"7","msgId":"1"
}
As you can see there are 2 attributes named fromTime and toTime which has a :
So while parsing this in Java, I used
JSONObject ruleFormJSON = JSONObject.fromString(ruleFormJSONString);
String fromTime = (String)ruleFormJSON.getString("fromTime");
String toTime = (String)ruleFormJSON.getString("toTime");
I am getting a NumberFormatException which is
java.lang.NumberFormatException: For input string: "18:00"
So please suggest me how, to get the value in the corresponding String variable.
Any help will be appreciated.
It seems there is an error on this line:
"listOfBusinessdays":"1","2","5","6","7"],
A closed bracket square but no open bracket before.
May be this hang up the parser.
Related
I'm using Json Path library to parse JSON. I've following json which has key with space:
{
"attributes": {
"First Name": "Jim",
"Last Name": "Rohn"
}
}
In order to get value of First Name, I wrote code like (where json is object which holds above json) -
String firstName = JsonPath.from(json).getString("attributes.First Name");
But it results into following error -
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found 'Attributes' # line 1, column 67.
.First Name
Could you please suggest how to get values of key having spaces using json-path library?
Try using bracket notation for First Name as follows:
String firstName = JsonPath.from(json).getString("attributes.['First Name']");
UPDATE
Sorry for mixing different JsoPath libraries up.
If you are using com.jayway.jsonpath, try following way for escaping:
DocumentContext jsonContext = JsonPath.parse(json);
String firstName = jsonContext.read("$.attributes.['First Name']");
But if you are using ***.restassured.json-path, please use this one:
String firstName = JsonPath.from(json).getString("attributes.'First Name'");
You have to escape the key with single quotes
Use below code:
String firstName = JsonPath.from(json).getString("'attributes.First Name'");
If you are using io.restassured.path.json.JsonPath library then Escape Sequences is required in the path expression.
String firstName = JsonPath.from(json).getString("attributes.\"First Name\"");
\" <-- Insert a double quote character in the text at this point.
So your path expression looks like (attributes."First Name") and can be parsed by JsonPath library
I have a malformed json array string which I get from an API call as follows:
[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]
There is a double quote before open square bracket in the value of Response Msg property.
Is there a way to convert this into Java object ?
What I have tried so far:
I have used Jackson to parse it as follows but it gives error
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new ResponseNameStrategy());
Response[] response = mapper.readValue(strOutput1, Response[].class);
Error: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
I have also tried using Gson to parse it but it also gives error
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Response[] response = gson.fromJson(strOutput1, Response[].class);
Error: Expected BEGIN_ARRAY but was STRING at line 1 column 35 path $[0].ResponseMsg
I have gone through the following links on StackOverflow but none of them has addressed my issue:
How to Convert String Array JSON in a Java Object
Convert a JSON string to object in Java ME?
JSON Array to Java objects
Convert json String to array of Objects
converting 'malformed' java json object to javascript
I think the answer is in the comments, you appear to be trying to solve the issue on the wrong place.
You are receiving json which you wish to parse into java objects, unfortunately the json is malformed so will not parse.
As a general rule you should never be trying to solve the symptom, but should look for the root cause and fix that, it may sound trivial but fixing symptoms leads to messy, unpredictable, and unmaintainable systems.
So the answer is fix the json where it is being broken. If this is something or of your control, while you wait for the fix, you could put a hack in to fix the json before you parse it.
This way you won't compromise your parsing, and only have a small piece of string replacement to remove when the third party has fixed the issue. But do not go live with the hack, it should only be used during development.
As i mentioned in the comment, you should prepare your service response in order to parse it.
I implemented an example:
public class JsonTest {
public static void main(String args[]) throws JsonProcessingException, IOException{
String rawJson =
"[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]";
String goodJson = "{"+rawJson.split("[{{.}]")[2]+"}";
ObjectMapper mapper = new ObjectMapper();
final ObjectNode node = mapper.readValue(goodJson, ObjectNode.class);
System.out.println("Pretty Print: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
System.out.println("Just code: " + node.get("Code"));
}
}
Which returns:
This is how I finally solved my issue:
String inputJsonStr = "[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Claim has been added successfully.\"}"
+ "]\"}]";
int indexOfRes = inputJsonStr.indexOf("ResponseMsg");
if(inputJsonStr.substring(indexOfRes+13,indexOfRes+14).equals("\""))
{
inputJsonStr = inputJsonStr.substring(0,indexOfRes+13) + inputJsonStr.substring(indexOfRes+14);
}
int indexOfFirstClosingSquare = inputJsonStr.indexOf("]");
if(inputJsonStr.substring(indexOfFirstClosingSquare+1, indexOfFirstClosingSquare+2).equals("\"")) {
inputJsonStr = inputJsonStr.substring(0, indexOfFirstClosingSquare+1)+inputJsonStr.substring(indexOfFirstClosingSquare+2);
}
Now inputJsonStr contains a valid json array which can be parsed into Java custom object array easily with gson as given in this SO link:
Convert json String to array of Objects
I'm kinda getting frustrated after searching and trying around everything my mind came up with...
I try to parse a JSON file into a list or array of MyObject. I found this post Link and played around with the code. But now I always get the same Exception, whatever I do/change in the JSON file.
Exception I get:
SyntaxError: JSON.parse: unexpected non-digit at line 1 column 2 of the JSON data
What I tried:
I reduced the file to just 2 objects not containing some special stuff to make sure it works. It doesnt..
Validating the json file with an online tool
All different types of importing the JSON as object list/array from 1
playing around with the JSON file
Heres the current code for importing
List<MyClass> myObjects = Arrays.asList(mapper.readValue(content, MyClass[].class));
JSON
[
{
"name":"1000.1000",
"maskId":"1000",
"fieldId":"1000",
"i18nKey":"debugLabel_1",
"label":"Logo",
"tooltip":" ---"
},
{
"name":"1000.1000",
"maskId":"1000",
"fieldId":"1000",
"i18nKey":"debugLabel_1",
"label":"Logo",
"tooltip":" ---"
}
]
MyClass
public class MyClass{
String name;
String maskId;
String fieldId;
String i18nKey;
String label;
String tooltip;
public MyClass(String name, String maskId, String fieldId, String i18nKey, String tooltip, String label) {
this.name = name;
this.maskId = maskId;
this.fieldId = fieldId;
this.i18nKey = i18nKey;
this.tooltip = tooltip;
this.label = label;
}
// Getter + Setter
}
Thanks for advices in advance.
It seems that your class expects to receive a number for it's property and sees string.
This should work:
[
{
"name":"1.1",
"maskId":1,
"fieldId":"1",
"i18nKey":"test1",
"label":"Test 1",
"tooltip":"---"
},
{
"name":"1.2",
"maskId":1,
"fieldId":"2",
"i18nKey":"test2",
"label":"Test 2",
"tooltip":"---"
}
]
Gson gson = new GsonBuilder().create();
final String jsonString = gson.toJson(mapper.readValue(content, MyClass[].class);
try this, i think it will work
I solved it... but I still cant tell what the problem was.
I recreated all the files and Classes and nowit works... kinda strange
But thanks for the help!
i have a JSON:
String jsonString = "{"Tech":"{id :[""],techInside :["Java","C++"]}","id1":"","state":""}";
So i need the value of techInside. How do i access that > I have tried:
JSONObject obj = new JSONObject(jsonString);
string techInside = obj.getJSONObject("Tech").getJSONArray("techInside");
But it gave me an exception:org.json.JSONException: Expected a ',' or '}' at 17.Tried Many other ways but spent a lot of time on it. Need some suggestions please.
Note: i am using escape characters in the string.So please ignore about the escaping characters in the jsonString
Your JSON is invalid. There should be no "" around objects ({}).
Try with this JSON-String:
String jsonString = "{\"Tech\":{\"id\":[\"\"], \"techInside\":[\"Java\", \"C++\"]}, \"id1\":\"\", \"state\":\"\"}"
Or without escaping
{"Tech":{"id":[""], "techInside":["Java", "C++"]}, "id1":"", "state":""}
I think the kind of json you are looking for is
{"Tech": {"id" : "", "techInside" : ["Java","C++"]},"id1":"","state":""}
Not sure, what your requirement is.
When I use Gson (JsonParser.parse) to decode the following:
{ "item": "Bread", "cost": {"currency": "\u0024", "amount": "3"}, "description": "This is bread\u2122. \u00A92015" }
The "currency" element is returned as a string of characters (and is not converted to a unicode character). Is there a setting or method in Gson that could help me?
If not, is there any way in Android to convert a string that contains one or more escaped character sequences (like "\u0024") to an output string with unicode characters (without writing my own and without using StringEscapeUtils from Apache)?
I'd like to avoid adding another library (for just one small feature).
Update
Looks like the server was double escaping the back slash in the unicode escape sequence. Thanks everyone for your help!
Is it only me or is it really more complicated than simply using TextView's setText() method? Anyhow, following is working just fine on my end with the given sample json (put the sample to assets and read it using loadJSONFromAsset()):
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(loadJSONFromAsset());
JsonObject obj = element.getAsJsonObject();
JsonObject cost = obj.getAsJsonObject("cost");
JsonPrimitive sign = cost.get("currency").getAsJsonPrimitive();
TextView tv = (TextView)findViewById(R.id.dollar_sign);
tv.setText(sign.getAsString());
Gson returns "$". Something is wrong in your set up.
String s = "{ \"item\": \"Bread\", \"cost\": {\"currency\": "
+ "\"\\u0024\", \"amount\": \"3\"}, \"description\": "
+ "\"This is bread\\u2122. \\u00A92015\" }\n";
JsonElement v = new JsonParser().parse(s);
assertEquals("$", v.getAsJsonObject().get("cost").getAsJsonObject()
.get("currency").getAsString());
You can parse it as a hex number
char c = (char)Integer.parseInt(str.substring(2), 16);