JSON Object creation is failing - java

I have json file which i down from internet and saved to my app. Then i read this file and create json object . But i am not able to create json object .
This is the exception I am getting
org.json.JSONException: Expected literal value at character 3 of { \"resources\": { ..........
Below is my code to read input stream and create json object
private JSONObject readFileFromInpputStream(InputStream inst) throws JSONException
{
// TODO Auto-generated method stub
StringBuilder responseStrBuilder=null;
try {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inst, "UTF-8"));
responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null){
responseStrBuilder.append(inputStr);
}
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = responseStrBuilder.toString();
String k=str.replace("\"", "\\\"");
// String m =k.replaceAll("\t", "");
// String s= m.replaceAll("\n", "");
//String p = s.replaceAll("\\s", "");
Log.i(loggerName, loggerName + " str " +str);
//Log.i(loggerName, loggerName + " k " +p);
JSONObject obj = new JSONObject(k);
return obj;
}
Below is output string
{
"resources": {
"-xmlns:xliff": "urn:oasis:names:tc:xliff:document:1.2",
"string": [
{
"name": "sample1",
"value": "To <xliff:g id=\"receiver_name\"> Europe </xliff:g>"
},
{
"name": "cdata",
"value": "<![CDATA[<p>Text<p>]]>"
},
{
"name": "content_description_sample",
"value": " <b>Something</b>"
},
{
"name": "countdown",
"value": " <xliff:g id="time" example="5days">%1$s</xliff:g> until holiday"
},
{
"name": "picker_combined_view_fmt",
"value": " Combined view (<xliff:g id="count">%s</xliff:g>)"
},
{
"name": "configure_email_text",
"value": "No corporate email accounts have been configured on this device. To configure them, click <b>Here</b> "
},
{
"name": "invalid_credentials",
"value": "Authentication failed. Enter valid credentials."
},
{
"name": "link",
"value": "<b>Hello World</b> This is a test of the URL Example"
},
{
"name": "bold",
"value": "<b>This text is bold</b>"
},
{
"name": "emphasis",
"value": "<em>This text is emphasized</em>"
},
{
"name": "check_availability_button",
"value": "Check availability How are you"
}
],
"string-array": [
{
"name": "Array1",
"item": [
"en_US",
"en_GB"
]
},
{
"name": "Array2",
"item": [
"en_US",
"en_GB"
]
}
]
}
}{
\"resources\": {
\"-xmlns: xliff\": \"urn: oasis: names: tc: xliff: document: 1.2\",
\"string\": [
{
\"name\": \"sample1\",
\"value\": \"To<xliff: gid=\\"receiver_name\\">Europe</xliff: g>\"
},
{
\"name\": \"cdata\",
\"value\": \"<![
CDATA[
<p>Text<p>
]
]>\"
},
{
\"name\": \"content_description_sample\",
\"value\": \"<b>Something</b>\"
},
{
\"name\": \"countdown\",
\"value\": \"<xliff: gid=\"time\"example=\"5days\">%1$s</xliff: g>untilholiday\"
},
{
\"name\": \"picker_combined_view_fmt\",
\"value\": \"Combinedview(<xliff: gid=\"count\">%s</xliff: g>)\"
},
{
\"name\": \"configure_email_text\",
\"value\": \"Nocorporateemailaccountshavebeenconfiguredonthisdevice.Toconfigurethem,
click<b>Here</b>\"
},
{
\"name\": \"invalid_credentials\",
\"value\": \"Authenticationfailed.Entervalidcredentials.\"
},
{
\"name\": \"link\",
\"value\": \"<b>HelloWorld</b>ThisisatestoftheURLExample\"
},
{
\"name\": \"bold\",
\"value\": \"<b>Thistextisbold</b>\"
},
{
\"name\": \"emphasis\",
\"value\": \"<em>Thistextisemphasized</em>\"
},
{
\"name\": \"check_availability_button\",
\"value\": \"CheckavailabilityHowareyou\"
}
],
\"string-array\": [
{
\"name\": \"Array1\",
\"item\": [
\"en_US\",
\"en_GB\"
]
},
{
\"name\": \"Array2\",
\"item\": [
\"en_US\",
\"en_GB\"
]
}
]
}
}
and below is the exception i am getting
org.json.JSONException: Expected literal value at character 3 of { \"resources\": { ..........
What am I doing wrong?

There is no reason to escape quotation marks("). They are part of how the json object constructor identifies strings.
Just using
JSONObject obj = new JSONObject(str);
should be fine.
In addition,
in " Combined view (%s)" the two quotation marks are treated as string delimiters and SHOULD be escaped, but it indicates a problem with the server you got this message from. Escaping these yourself can be impossible because there is no sure way to know which quotation marks are real and which are part of the text.

On validating your JSON output through Jlint it gives validation error, but on removing space on line 2 of your output(is the space intentional ? or you added it on posting question by mistake?)
"cdata", "value": "Text
]]>" }, { "nam
it validates successfully.
In any case whether the space is initial source of error or not ,like CurlyCorvus said, simply pass the String to new JSONObject(str); without escaping the ".

Thans Mustafa and Curly.
The issue was due to quotes mark in tag
for ex in original one value is
"value": " %1$s until holiday"
It worked fine when I replaced it to
"value": " %1$s until holiday"
So I guess when quotes is present inside it consider it as new object.

Related

Need JOLT spec for array input JSON

I am working on transforming a complex json using JOLT.
Input JSON:
{ "data":
[
{
"fieldname": "Name",
"fieldvalue": [ "John Doe" ]
},
{ "fieldname": "Title",
"fieldvalue": [ "Manager" ]
},
{ "fieldname": "Company",
"fieldvalue": [ "Walmart" ]
}
] }
Expected Output:
{
"finalPayload":{
"PI":{
"EmpName":"John Doe",
"EmpRole":"Manager"
},
"Company":"Walmart"
}
}
I am unable to understand how to access and assign "fieldvalue" in output based on "fieldname". Please help me with the JOLT spec.
Note: The order of name, title and company in input JSON will be jumbled and random meaning its not mandatory that under "data" array first object will be related to "Name" only.
Hi hope this helps you in resolving your issue.
You can have condition in Jolt too, by going inside the variable and checking the fieldname.
[
{
"operation": "shift",
"spec": {
"data": {
"*": {
"fieldname": {
"Name": {
"#(2,fieldvalue)": "finalPayload.PI.EmpName"
},
"Title": {
"#(2,fieldvalue)": "finalPayload.PI.EmpRole"
},
"Company": {
"#(2,fieldvalue)": "finalPayload.Company"
}
}
}
}
}
},
{
"operation": "cardinality",
"spec": {
"finalPayload": {
"PI": {
"EmpName": "ONE",
"EmpRole": "ONE"
},
"Company": "ONE"
}
}
}
]
May I introduce an alternative library to solve the issue.
https://github.com/octomix/josson
implementation 'com.octomix.josson:josson:1.3.21'
-------------------------------------------------
Josson josson = Josson.fromJsonString(
"{\"data\":[{\"fieldname\":\"Name\",\"fieldvalue\":[\"JohnDoe\"]},{\"fieldname\":\"Title\",\"fieldvalue\":[\"Manager\"]},{\"fieldname\":\"Company\",\"fieldvalue\":[\"Walmart\"]}]}");
JsonNode node = josson.getNode(
"map(" +
" finalPayload: map(" +
" PI: map(" +
" EmpName: data[fieldname='Name'].fieldvalue[0]," +
" EmpRole: data[fieldname='Title'].fieldvalue[0]" +
" )," +
" Company: data[fieldname='Company'].fieldvalue[0]" +
" )" +
")");
System.out.println(node.toPrettyString());
Output
{
"finalPayload" : {
"PI" : {
"EmpName" : "JohnDoe",
"EmpRole" : "Manager"
},
"Company" : "Walmart"
}
}

RegEx to find value in JSON

I need to write a RegEx on a JSON to match everything that starts with {$ and ends with }
I tried with /{(.*?)}/g and it seemingly works fine but if you see the image below it also matches the other text so how do I explicitly write a RegEx for my requirement
The reason for the ask is I need to find values with {$*} and replace them with a string
Below is my JSON
{
"name": "{$StubName}",
"request": {
"method": "POST",
"url": "/marks/{$Name}",
"bodyPatterns": [
{
"equalToJson": "{\n \"name\": \"{$RequestName}\",\n \"job\": \"{$Role}\"\n}"
}
]
},
"response": {
"status": "201",
"headers": {
"Content-Type": "application/json"
},
"body": "{\n \"name\": \"{$RequestName}\",\n \"job\": \"{$Role}\",\n \"id\": \"{$id}\",\n \"createdAt\": \"{$Time}\"\n}"
}
}
You can use \{\$\w*\}
Regex demo

Different answer interrogate elasticsearch with java or cmd

I've got a problem when I interrogate elasticsearch with java.
So when I execute this command in cmd, I retrieve the exact desired answer :
curl -XGET "localhost:9200/movies2/movie/_search?pretty=1" -d #queryMovies
And here is queryMovies:
{
"query":{
"bool": {
"must" : { "match": { "fields.title": "Star Wars" }},
"should" : { "match": { "fields.directors": "George Lucas" }}
}
}
}
But with this java code where the query is actually the same :
public class Connection {
public static void main(String[] args) throws IOException {
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
client.addTransportAddress(
new InetSocketTransportAddress(
InetAddress.getByName("localhost"), 9300));
StringBuilder query = new StringBuilder();
query.append("{\n" +
"\"query\":{\n" +
" \"bool\": {\n" +
" \"must\" : { \"match\": { \"fields.title\": \"Star Wars\" }},\n" +
" \"should\" : { \"match\": { \"fields.directors\": \"George Lucas\" }}\n" +
" }\n" +
" }\n" +
"}\n");
String indexToSearch = "movies2";
String docType = "movie";
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryBuilder queryBuilder = QueryBuilders.simpleQueryStringQuery(query.toString());
searchSourceBuilder.query(queryBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = client.prepareSearch(indexToSearch)
.setTypes(docType)
.setSource(searchSourceBuilder)
.execute()
.actionGet();
} catch (Exception e) {
System.out.println("Error performing search on index[" + indexToSearch + "] and docType[" + docType + "] using query[" + query.toString() + "]. Error is: " + e.getLocalizedMessage());
}
//write the retrieved json in a file.json
CrunchJSONFileWrite crunchJSONFileWrite = new CrunchJSONFileWrite("test");
crunchJSONFileWrite.fillFile(searchResponse);
client.close();
}
}
I retrieve the answer I want but there are some extra unwanted part in the answer like this one where the director isn't George Lucas or, Star Wars isn't in the title:
{
"_index": "movies2",
"_type": "movie",
"_id": "4484",
"_score": 11.219259,
"_source": {
"fields": {
"directors": [
"Barry Skolnick"
],
"release_date": "2001-12-26T00:00:00Z",
"rating": 6.3,
"genres": [
"Comedy",
"Drama",
"Sport"
],
"image_url": "http://ia.media-imdb.com/images/M/MV5BMTU2ODk0OTMyNF5BMl5BanBnXkFtZTcwMTcyMTMyMQ##._V1_SX400_.jpg",
"plot": "A soccer star jailed for assault leads a group of inmates in a match against prison guards.",
"title": "Mean Machine",
"rank": 4484,
"running_time_secs": 5940,
"actors": [
"Vinnie Jones",
"David Kelly",
"David Hemmings"
],
"year": 2001
},
"id": "tt0291341",
"type": "add"
}
}
I checked for topics like this one query elasticsearch with java with JSON but none helped
Thank you for your reading and help

JSON Unterminated object at character android

I have a .json file that contains JSON data. I created this file by simply Ctrl + C and Ctrl + V (from server output) Here's part of my file
[{
"ID": "109",
"objectTypeID": "1",
"names": [{
"ID": 1,
"code": "lt",
"value": "Trak\u0173 salos pilis "
}, {
"ID": 2,
"code": "en",
"value": "Trakai Island Castle"
}, {
"ID": 3,
"code": "ru",
"value": "\u0422\u0440\u0430\u043a\u0430\u0439\u0441\u043a\u0438\u0439 \u0437\u0430\u043c\u043e\u043a"
}, {
"ID": 4,
"code": "de",
"value": "Kasteel van Trakai"
}],
"descriptions": [{
"ID": 1,
"code": "lt",
"value": "<div><strong>Paslap\u010di\u0173 m\u0117g\u0117jams ir ieškotojams<\/strong><\/div>\r\n\r\n<div>Tiems, kurie domisi istorija, kurie m\u0117gsta paslaptingas vietoves, \u012f Trakus atkeliauti b\u016btina. Trak\u0173 pilis yra vienas labiausiai turist\u0173 lankom\u0173 objekt\u0173 Lietuvoje......"
}]
}]
I have saved this file with utf-8 encoding
As you can see there are lot of Unicode Characters and html elements like <div>, <strong> and so on....
Now I want to parse this file. Here's my java/android code
private String getJSONString(File file){
try {
FileInputStream is = new FileInputStream(file.getAbsolutePath());
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void object_parser(File file){
String jsonString = getJSONString(file);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.d("OBJECTS_LIST_AAA", jsonArray.toString());
} catch (JSONException e) {
Log.d("OBJECTS_LIST_ERROR", e.getMessage()); // print error
e.printStackTrace();
}
}
}
and I get this error Unterminated object at character 5641 of [{"ID":"109","objectTypeID":"1","names":[{"ID":1,"code":"lt","value":"Trak\u0173 salos pilis "},......
I think that formating is missing in this file.
Your Every "Restaurant "Avilys"" like data are invalid, You have to replace all of them with "Restaurant Avilys" as a single String value quoted with only two quotation marks. There are many similar cases like these as well. And note that the part you posted is clearly valid and can be parsed easily, Here is no such errors.

Aws Json Exception - A JSONObject text must begin with '{' at 1 [character 2 line 1]

I am facing an error with json , although
System.out.println((int)text.trim().charAt(0));
returns 123 which means it does starts with curly bracket.
I am totally out of ideas and i also tried to trim() instead of toString().
InputStream bis = new ByteArrayInputStream(bytes);
InputStream is = new GZIPInputStream(bis);
byte[] unPackedBytes = IOUtils.toByteArray(is);
String text = new String(unPackedBytes, "UTF-8");
JSONObject obj = new JSONObject(text.toString());
It is so weird because when i input the json it doesn't give any errors but when i give the compressed file it does gives errors but the output of the compressed file is exactly same with json, so i am confused.
This is the Json.
{
"id": 123,
"providerId": 123,
"externalTrackId": "068d",
"genres": [
{
"genre": "Rap/Hip-Hop",
"subGenre": "Rap/Hip-Hop"
}
],
"title": {
"title": "The "
},
"artists": [
{
"name": {
"primary": {
"value": "J-"
}
},
"role": "Artist"
}
],
"contributors": [],
"release": {
"id": 123,
"title": {
"title": "The "
},
"artist": {
"primary": {
"value": "J"
}
},
"externalId": "gener2cec9477d",
"genre": {
"genre": "Rap/Hip-Hop",
"subGenre": "Rap/Hip-Hop"
},
"copyrightYear": 0
},
"trackCountInMedia": 0,
"mediaCountInRelease": 0,
"signature": {
"url": "https:",
"id": 123,
"type": "FULL",
"audioType": "MUSIC",
"creation": "2013-"
},
"label": "Unknown",
"lastMod": "2013-01-04T16:02:57.607Z"
}
Cheers
I found my answer , it was a mistake of me because i wasn't decoding data from Base64.
It's weird because it was seemed like exactly same output but it wasn't.
Thanks to #Jhanvi for trying to help me.

Categories