Escape "[" bracket from json - java

I know that "[" brackets are used in json to specify a list such as:
"Value":["A","B"]
However I want to use those brackets as is in json like "Value":"[A TO B]"
since in the future this json string gets mapped to a URL:
I am using java where while using json parser it gives me an error.
Is there a way I can escape "[" brackets.

As long as you keep it in quotes, it is valid JSON. Try the code below in a validator
{
"key": "mykey",
"Value": "[A TO B]"
}
It returns: valid!

Related

How to get value with an underscore inside a string from Elasticsearch using QueryBuilder in Java?

I'm using Elasticsearch 3.2.7 and ElasticsearchRepository.search() which takes QueryBuilder as an argument (doc)
I have a BoolQueryBuilder and use it like this:
boolQuery.must(termQuery("myObject.code", value);
var results = searchRepository.search(boolQuery);
The definition of the field code is as follows:
"myObject": {
"properties": {
"code": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
The issue is, when I search with a value that has underscore inside, for example: FOO_BAR then it doesn't return any results. When I search with other values that have either leading or trailing underscore then it's fine.
I've read that ES may ignore the special character and split the words inside by it so there's a need for an exact match search. But I also read that the keyword setting guarantees that. So right now I'm confused.
yes, you are correct, using keyword field you can achieve the exact match, you need to use the below query
boolQuery.must(termQuery("myObject.code.keyword", value); --> note addition of keyword
var results = searchRepository.search(boolQuery);
you can use the analyze API to see the tokens for your indexed documents and search term, and basically your tokens in index must match search terms tokens, in order ES to return the match :)

JsonPath Fetch string after filter

I am using Jayway JsonPath 2.2 version in JAVA. I have few questions on the same.
Sample JSON:
{
"l5": [
{
"type": "type1",
"result": [
"res1"
]
},
{
"type": "type2",
"result": [
"r1"
]
}
]
}
I want to fetch a string after a filter is applied?
Eg:
Path used to fetch a string is l5[?(#.type == 'type2')].type
Expected result: type2 (string), but getting ["type2"] (array)
Please correct the path if i am doing anything wrong to fetch it as a string?
Unable to index the resultant array after the filter is applied. How can i achieve the same?
Eg:
If i use the path l5[?(#.type == 'type2')][0], instead of returning me the first JSONObject it returns []
Is it possible to extract substring from a string using jsonPath?
Something like l5[0].type[0,2] => res
Note: I cannot do any operation in JAVA, as i wanted to keep the library generic?
The return value of jsonPath is always an array, quoted from here.
So, the operation1 you are trying is not possible i.e. String value will never be returned.
Even operation 2 and operation 3 doesn't look feasible with jayway jsonpath.
Good read on jayway Jsonpath.
Only Possible way for operation 1 and 2 looks something like below:-
String jsonpath="l5[?(#.type == 'type2')].type";
DocumentContext jsonContext = JsonPath.parse(jsonString);
List<String> typeDataList= jsonContext.read(jsonpath);
System.out.println(typeDataList.get(0)); //type2

How to parse escaped Json using JSONObject in android

I'm unable to parse escaped json string through JSONObject, while trying to parse it, I always get an Unterminated Object error. But when I manually remove all of the escape characters from the json string, JSONObject parses it successfully.
But the problem is that for complex or nested json strings, I don't want to remove escape characters, because for nested structures, unescaping the characters results in an invalid json string.
This is the json string after removing escapes characters and I get unterminated object error due to invalid json when parsing through JSONObject
{"result":"unknown","message":"{"firebase":"unknown"}","sender":"unknown"}
This is the unescaped json string
{"result":"unknown","message":"{\"firebase\":\"unknown\"}","sender":"unknown"}
If you look at the json you are constructing it in wrong format.
In case of escaped json
{
"result":"unknown",
"message":"{"firebase":"unknown"}",
"sender":"unknown"
}
the json object "message" is having value "{" and firebase is causing exception.
In the the escaped json "message":{"firebase":"unknown"} will form valid json.

Unterminated string at character while parsing the JSON

I have a JSON which the jsonlint shows as a valid JSON but when I call
JSONObject rootObj=new JSONObject(orderJsonStr);
am getting org.json.JSONException: Unterminated string at character 13755, the place where it is break has "value": "12312&", it is breaking in place of '&'. Do we need to escape & or can we use a urlEncoder to encode the JSON?
For special characters in your json meesage like \ , # , & , # etc.. first convert them into their respective HEX value and then send your message.

Reading Json String using Gson results error "not a JSON Array"

In my project i have a complex json response. I want to read it by GSon.
JSON : {'FoodMenuRS':{'Results':[{'Items':{'Item':[{'#Id':'24'},{'#Id':'24'}]}}, {'Items':{'Item':{'#Id':'24'}}}]}}
It contains a JSONArray with first "Item" and JSONObject with second one. Hence its call results in error,
failed to deserialize json object {"#Id":"24"} given the type java.util.List<com.servlet.action.ItemInfo> and java.lang.IllegalStateException: This is not a JSON Array.
Please help how i should handle this scenario. Thanks.
The string you are showing is a JSONObject not a JSONArray. So, in this case you first of all have to get the JSONObject and perform further decoding on that JSONObject.
JSONObject - {}
JSONArray - []
And indeed JSONObject or JSONArray should be encoded using Double-quotes(")
Your JSON is valid, but not for the doble quotes (") because JSON supports simple quotes (') and no quotes in the key name. See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Colle
However this JSON have key names that begin with #. For JSON strings this character is valid at the beginning of the name (see right column http://www.json.org/) but for Java this names are illegal (see Naming section http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Specifically, names started with # are annotations and you can't use annotations tags to declare variables, fields, methods, etc.
This is not a valid JSON object. Strings in JSON are always encapsulated in double quotes ("). Contact the producer of that JSON and tell him to use a correct encoder.

Categories

Resources