Parse JSON String into JSONArray (Android) - java

i'm trying to parse a json string to a JSONArray element, but when i try i get "cannot be converted to JSONArray"
My string is this way (but way longer):
{
"mylist": {
"myinfo": {
"user_id": 6225804,
"user_name": "culo",
"user_watching": 1092,
"user_completed": 0,
"user_onhold": 0,
"user_dropped": 0,
"user_plantowatch": 0,
"user_days_spent_watching": 0
},
"anime": [{
"series_animedb_id": 1,
"series_title": "Cowboy Bebop",
"series_synonyms": "; Cowboy Bebop",
"series_type": 1,
"series_episodes": 26,
"series_status": 2,
"series_start": "1998-04-03",
"series_end": "1999-04-24",
"series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/4\/19644.webp",
"my_id": 0,
"my_watched_episodes": 0,
"my_start_date": "0000-00-00",
"my_finish_date": "0000-00-00",
"my_score": 0,
"my_status": 1,
"my_rewatching": 0,
"my_rewatching_ep": 0,
"my_last_updated": 1493924579,
"my_tags": ""
}, {
"series_animedb_id": 5,
"series_title": "Cowboy Bebop: Tengoku no Tobira",
"series_synonyms": "Cowboy Bebop: Knockin' on Heaven's Door; Cowboy Bebop: The Movie",
"series_type": 3,
"series_episodes": 1,
"series_status": 2,
"series_start": "2001-09-01",
"series_end": "2001-09-01",
"series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/6\/14331.webp",
"my_id": 0,
"my_watched_episodes": 0,
"my_start_date": "0000-00-00",
"my_finish_date": "0000-00-00",
"my_score": 0,
"my_status": 1,
"my_rewatching": 0,
"my_rewatching_ep": 0,
"my_last_updated": 1496668154,
"my_tags": ""
}, {
"series_animedb_id": 6,
"series_title": "Trigun",
"series_synonyms": "; Trigun",
"series_type": 1,
"series_episodes": 26,
"series_status": 2,
"series_start": "1998-04-01",
"series_end": "1998-09-30",
"series_image": "https:\/\/myanimelist.cdn-dena.com\/images\/anime\/7\/20310.webp",
"my_id": 0,
"my_watched_episodes": 0,
"my_start_date": "0000-00-00",
"my_finish_date": "0000-00-00",
"my_score": 0,
"my_status": 1,
"my_rewatching": 0,
"my_rewatching_ep": 0,
"my_last_updated": 1496668441,
"my_tags": ""
}, ETCETERA 1000 more like this one
I don't really care about the "mylist" or "myinfo" part, just the "anime" part is needed. There are about 1000 items.
I've validated my JSON and it is valid.
This is my code:
JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = new JSONArray(replacedString);
and here is where my issue begins. I've also tried this:
JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = object.getJSONArray("mylist");
and
JSONObject object = new JSONObject(replacedString);
JSONArray replacedResponse = object.getJSONArray("anime");
with similar results
What i'm I not seeing here? thanks in advance!

Please follow this code.
String stringObj = "[YOUR JSON]";
// first Convert string into JsonObject
try {
JSONObject jsonObject = new JSONObject(stringObj);
// Inside the above object you have "mylist" key and the respective JsonObject so
JSONObject myListObject = jsonObject.optJSONObject("mylist");
// Insdide mylist you have myinfo Json and anim JsonArray
if(myListObject == null) {
return;
}
JSONObject myinfoObject = myListObject.optJSONObject("myinfo");
JSONArray animeJsonArray = myListObject.optJSONArray("anime");
// check null for myinfoObject and animeJsonArray and do the operation
} catch (JSONException e) {
e.printStackTrace();
}

Related

Convert the flat Java Object that was created from the DB read, into nested Json object

The threaded comments are stored in Database as flat records with commenId and ParentCommentId. Like below.
commentId : 1
userId    : 815
userFName:Joe
userLName:Doe
timeStamp:12345678888
commentText:""
parentCommentId:0
commentId : 2
userId    : 615
userFirstName:Ken
userLastName:Tait
timeStamp:12345678988
commentText:"Comment text"
parentCommentId:1
commentId : 3
userId    : 415
userFirstName:Brain
userLastName:Dell
timeStamp:12345678
commentText:"Comment text"
parentCommentId:0
I build the Java object using the following Java class
public class Comment {
int commentId;
int userId;
String userFName;
String userLName;
long timeStamp;
String commentText;
int parCommId;
}
List<Comment> comments;
I have the List of comments object. Now I have to traverse the list and convert this list of comment object into nested Json object. The comment objects with parCommId == 0 are the top level comment and the other comment objects (parCommId != 0) should be nested under the commentId of the comment object.
In the above example, the output should be nested like below
CommentId_1
CommentId_2
CommentID_3
As suggested in the comments, let's add a List<Comment> field in Comment.class.
Then, assuming the input from the DB is:
List<Comment> comments = Arrays.asList(
new Comment(1, 6, "John", "Snow", 0, "asd", 0),
new Comment(2, 6, "Tif", "Snow", 0, "asd2", 1),
new Comment(3, 6, "Yur", "Snow", 0, "asd", 2),
new Comment(4, 6, "Mrr", "Snow", 0, "asd", 0),
new Comment(5, 6, "Mrr", "Snow", 0, "asd", 2)
);
You can do the following:
Map<Integer, List<Comment>> parentToComments = comments.stream()
.collect(Collectors.groupingBy(Comment::getParCommId));
comments.forEach(comment -> {
List<Comment> children = parentToComments.get(comment.getCommentId());
comment.setChildren(children);
});
ObjectMapper objectMapper = new ObjectMapper();
String commentsJson = objectMapper.writeValueAsString(parentToComments.get(0));
Output:
[{
"commentId": 1,
"userId": 6,
"userFName": "John",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": [{
"commentId": 2,
"userId": 6,
"userFName": "Tif",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd2",
"parCommId": 1,
"children": [{
"commentId": 3,
"userId": 6,
"userFName": "Yur",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}, {
"commentId": 5,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}]
}]
}, {
"commentId": 4,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": null
}]

Customise the Json in Android Java

I have Json like this..
I used Gson
[
{
"quantity": 12.0,
"product_gid": 15
},
{
"quantity": 6.0,
"product_gid": 18
}
]
I used Json.put
{
"ACTION": "Insert",
"soheader_gid": 0,
"emp_gid": 59,
"custid": 120
}
Now I need to customize the data as
{
"parms": {
"emp_gid": 59,
"soheader_gid": 0,
"custid": "120",
"ACTION": "Insert",
"data": {
"sodetails": [
{
"quantity": 12.0,
"product_gid": 15
},
{
"quantity": 6.0,
"product_gid": 18
}
]
}
}
}
Even this is simple in Python or .net, I am confused how to do in Java Android.
Hi you can try below code to construct your json,
String message;
JSONObject json = new JSONObject();
JSONObject json1 = new JSONObject();
JSONObject json2 = new JSONObject();
JSONObject json3 = new JSONObject();
JSONObject json4 = new JSONObject();
JSONArray jsonArray=new JSONArray();
json1.put("emp_gid", 59);
json1.put("soheader_gid", 0);
json1.put("custid", 120);
json1.put("ACTION", "Insert");
json1.put("data", json2);
json.put("parms", json1);
json3.put("quantity", 12.0);
json3.put("product_gid", 15);
json4.put("quantity", 6.0);
json4.put("product_gid", 18);
jsonArray.put(json3);
jsonArray.put(json4);
json2.put("sodetails", jsonArray);
message = json.toString();
#NOTE: above code is just a process to convert your two json in single one.
We done it by
JSONObject Full_Json = new JSONObject();
JSONObject params_Json = new JSONObject();
params_Json.put(Constant.emp_gid, Integer.parseInt(UserDetails.getUser_id()) );
params_Json.put(Constant.soheader_gid, 0);
params_Json.put(Constant.customer_gid, cust_gid);
params_Json.put(Constant.Action, "Insert");
params_Json.put(Constant.Data, new JSONObject().put(Constant.sodetails, soDetails));
Full_Json.put(Constant.params, params_Json);
soDetails is a Json array

Converting String into Object Json Array using Java [duplicate]

This question already has answers here:
How to read json file into java with simple JSON library
(21 answers)
Closed 5 years ago.
I have this string which located inside external file.
{
"IsValid": true,
"LiveSessionDataCollection": [
{
"CreateDate": "2017-12-27T13:29:06.595Z",
"Data": "Khttp://www8.hp.com/us/en/large-format-printers/designjet-printers/products.html&AbSGOX+SGOXpLXpBF8CXpGOA9BFFPconsole.info('DeploymentConfigName%3DRelease_20171227%26Version%3D1')%3B&HoConfig: Release_20171227&AwDz//////8NuaCh63&Win32&SNgYAJBBYWCYKW9a&2&SGOX+SGOXpF/1en-us&AAAAAAAAAAAAQICBCXpGOAAMBBBB8jl",
"DataFlags": 8,
"DataFlagType": 264,
"LegacyLiveSessionDataType": null,
"LiveSessionId": 1545190526042650,
"MessageNumber": 0,
"StreamId": 0,
"StreamMessageId": 0,
"ProjectId": 201
},
{
"CreateDate": "2017-12-27T13:29:08.887Z",
"Data": "oDB Information Level : Detailed&9BbRoDB Annual Sales : 55000000&BoDB Audience : Mid-Market Business&AoDB%20Audience%20Segment%20%3A%20Retail%20%26%20Distribution&AoDB B2C : true&AoDB Company Name : Clicktale Inc&AoDB SID : 120325490&AoDB Employee Count : 275&AoDB Employee Range : Mid-Market&AoDB%20Industry%20%3A%20Retail%20%26%20Distribution&AoDB Revenue Range : $50M - $100M&AoDB Sub Industry : Electronics&AoDB Traffic : High&AWB9tY/8bvOBBP_({\"a\":[{\"a\":{\"s\":\"w:auto;l:auto;\"},\"n\":\"div53\"}]})&sP_({\"a\":[{\"a\":{\"s\":\"w:auto;l:auto;\"},\"n\":\"div62\"}]})&FP_({\"r\":[\"script2\"],\"m\":[{\"n\":{\"nt\":1,\"tn\":\"SCRIPT\",\"a\":{\"async\":\"\",\"src\":\"http://admin.brightcove.com/js/api/SmartPlayerAPI.js?_=1514381348598\"},\"i\":\"script55\"},\"t\":false,\"pn\":\"head1\"}]})&8GuP_({\"a\":[{\"a\":{\"s\":\"t:0px;mt:0px;l:274.5px;ml:0px;\"},\"n\":\"div442\"}]})&SP_({\"a\":[{\"a\":{\"s\":\"t:0px;mt:0px;l:274.5px;ml:0px;\"},\"n\":\"div444\"}]})&D",
"DataFlags": 8,
"DataFlagType": 264,
"LegacyLiveSessionDataType": null,
"LiveSessionId": 1545190526042650,
"MessageNumber": 1,
"StreamId": 0,
"StreamMessageId": 1,
"ProjectId": 201
},
{
"CreateDate": "2017-12-27T13:29:08.971Z",
"Data": "P_({\"a\":[{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div105\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div114\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div123\"}]})&9B+8P_({\"a\":[{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div167\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div169\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div178\"}]})&JP_({\"a\":[{\"a\":{\"s\":\"mih:457px;\"},\"n\":\"div220\"},{\"a\":{\"s\":\"mih:457px;\"},\"n\":\"div229\"},{\"a\":{\"s\":\"mih:457px;\"},\"n\":\"div238\"}]})&FP_({\"a\":[{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div282\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div291\"},{\"a\":{\"s\":\"mih:480px;\"},\"n\":\"div300\"}]})&HP_({\"a\":[{\"a\":{\"s\":\"t:0px;mt:-92px;l:274.5px;ml:0px;\"},\"n\":\"div442\"}]})&HP_({\"a\":[{\"a\":{\"s\":\"t:0px;mt:-92px;l:274.5px;ml:0px;\"},\"n\":\"div444\"}]})&B",
"DataFlags": 8,
"DataFlagType": 264,
"LegacyLiveSessionDataType": null,
"LiveSessionId": 1545190526042650,
"MessageNumber": 2,
"StreamId": 0,
"StreamMessageId": 2,
"ProjectId": 201
},
{
"CreateDate": "2017-12-27T13:29:08.98Z",
"Data": "P_({\"r\":[\"object1\",\"param1\",\"param2\",\"param3\",\"param4\",\"param5\",\"param6\",\"param7\",\"param8\",\"param9\",\"param10\",\"param11\",\"param12\",\"param13\",\"param14\",\"param15\"],\"m\":[{\"n\":{\"nt\":1,\"tn\":\"OBJECT\",\"a\":{\"type\":\"application/x-shockwave-flash\",\"i\":\"LNK--1710e8cd-4820-4be0-8cf0-28d57402afd8LNK--1710e8cd-4820-4be0-8cf0-28d57402afd8\",\"width\":\"720\",\"height\":\"422\",\"c\":\"BrightcoveExperience BrightcoveExperienceID_1039\",\"seamlesstabbing\":\"undefined\"},\"i\":\"object3\"},\"t\":false,\"pn\":\"div443\",\"ps\":\"meta29\"},{\"n\":{\"nt\":1,\"tn\":\"SCRIPT\",\"a\":{\"type\":\"text/javascript\",\"src\":\"http://admin.brightcove.com/js/api/SmartPlayerAPI.js\"},\"i\":\"script56\"},\"t\":false,\"pn\":\"div443\",\"ps\":\"object3\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"allowScriptAccess\",\"v\":\"always\"},\"i\":\"param31\"},\"t\":false,\"pn\":\"object3\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"allowFullScreen\",\"v\":\"true\"},\"i\":\"param32\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param31\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"seamlessTabbing\",\"v\":\"false\"},\"i\":\"param33\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param32\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"swliveconnect\",\"v\":\"true\"},\"i\":\"param34\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param33\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"wmode\",\"v\":\"opaque\"},\"i\":\"param35\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param34\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"quality\",\"v\":\"high\"},\"i\":\"param36\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param35\"},{\"n\":{\"nt\":1,\"tn\":\"PARAM\",\"a\":{\"name\":\"bgcolor\",\"v\":\"FFFFFF\"},\"i\":\"param37\"},\"t\":false,\"pn\":\"object3\",\"ps\":\"param36\"}]})&9CAQ",
"DataFlags": 8,
"DataFlagType": 264,
"LegacyLiveSessionDataType": null,
"LiveSessionId": 1545190526042650,
"MessageNumber": 3,
"StreamId": 0,
"StreamMessageId": 3,
"ProjectId": 201
},
{
"CreateDate": "2017-12-27T13:29:09.413Z",
"Data": "P_({\"a\":[{\"a\":{\"s\":\"w:720px;h:422px;p:relative;\"},\"n\":\"div443\"},{\"a\":{\"s\":\"p:relative;\"},\"n\":\"div445\"}],\"r\":[\"script55\"],\"m\":[{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"spooler\",\"s\":\"d:block;o:0;\"},\"i\":\"div451\"},\"t\":false,\"pn\":\"div443\"},{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"ispl_sm\",\"s\":\"o:1;\"},\"i\":\"div452\"},\"t\":false,\"pn\":\"div451\"},{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"layer\",\"s\":\"o:1;\"},\"i\":\"div453\"},\"t\":false,\"pn\":\"div451\",\"ps\":\"div452\"},{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"spooler\",\"s\":\"d:block;o:0;\"},\"i\":\"div454\"},\"t\":false,\"pn\":\"div445\"},{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"ispl_sm\",\"s\":\"o:1;\"},\"i\":\"div455\"},\"t\":false,\"pn\":\"div454\"},{\"n\":{\"nt\":1,\"tn\":\"DIV\",\"a\":{\"c\":\"layer\",\"s\":\"o:1;\"},\"i\":\"div456\"},\"t\":false,\"pn\":\"div454\",\"ps\":\"div455\"}]})&9CA5P_({\"a\":[{\"a\":{\"s\":\"d:block;o:0.0282439;\"},\"n\":\"div451\"},{\"a\":{\"s\":\"o:0.989022;\"},\"n\":\"div453\"},{\"a\":{\"s\":\"d:block;o:0.0282439;\"},\"n\":\"div454\"},{\"a\":{\"s\":\"o:0.989022;\"},\"n\":\"div456\"}]})&W",
"DataFlags": 8,
"DataFlagType": 264,
"LegacyLiveSessionDataType": null,
"LiveSessionId": 1545190526042650,
"MessageNumber": 4,
"StreamId": 0,
"StreamMessageId": 4,
"ProjectId": 201
}
]
I am trying to parse it into JSON array object , when I searched for it in Google I found the following solution:
JSONArray jsonArray = new JSONArray("path_to_file_to_parse");
but when I wrote it inside my code I got an error. Is there another way to make it?
I am using json-simple version 1.1
Have you looked at Jackson Tree Model?
//first, you create a mapper object
ObjectMapper mapper = new ObjectMapper();
//then you create a JsonNode instance representing your JSON root structure
//you will need to define json yourself to run the code.
JsonNode root = null;
try {
root = mapper.readTree(json);
} catch (IOException e) {
System.out.println("Some Error");
}
//here you get the list of your session nodes
JsonNode list = root.path("LiveSessionDataCollection");
//then you can iterate through them and get any inner value
for (JsonNode session : list) {
//for example, you can get the create date or live session id.
System.out.println(session.path("CreateDate"));
System.out.println(session.path("LiveSessionId"));
}
I may not be understanding your question fully but I think this is what you're after.

Trying to parse JSON in Java (using Gson), getting MalformedJsonException

I am trying to get weather forecast data from the WeatherUnderground API.
So far I am using the following code:
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
JsonParser jp = new JsonParser();
JsonElement forecastJson = jp.parse(new InputStreamReader((InputStream) connection.getContent())).getAsJsonObject()
.getAsJsonObject().get("forecast")
.getAsJsonObject().get("simpleforecast")
.getAsJsonObject().getAsJsonArray("forecastday").get(1);
System.out.println("forecastJson = " + forecastJson.toString());
String date = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("date")
.getAsJsonObject().get("epoch").getAsString()));
String high = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("high")
.getAsJsonObject().get("celsius").getAsString()));
String low = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("low")
.getAsJsonObject().get("celsius").getAsString()));
String conditions;
try {
conditions = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("conditions").getAsString()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
The JsonElement forecastJson" I receive looks like this:
{
"date": {
"epoch": "1467046800",
"pretty": "7:00 PM CEST on June 27, 2016",
"day": 27,
"month": 6,
"year": 2016,
"yday": 178,
"hour": 19,
"min": "00",
"sec": 0,
"isdst": "1",
"monthname": "June",
"monthname_short": "Jun",
"weekday_short": "Mon",
"weekday": "Monday",
"ampm": "PM",
"tz_short": "CEST",
"tz_long": "Europe/Berlin"
},
"period": 2,
"high": {
"fahrenheit": "77",
"celsius": "25"
},
"low": {
"fahrenheit": "58",
"celsius": "14"
},
"conditions": "Partly Cloudy",
"icon": "partlycloudy",
"icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
"skyicon": "",
"pop": 0,
"qpf_allday": {
"in": 0,
"mm": 0
},
"qpf_day": {
"in": 0,
"mm": 0
},
"qpf_night": {
"in": 0,
"mm": 0
},
"snow_allday": {
"in": 0,
"cm": 0
},
"snow_day": {
"in": 0,
"cm": 0
},
"snow_night": {
"in": 0,
"cm": 0
},
"maxwind": {
"mph": 15,
"kph": 24,
"dir": "W",
"degrees": 260
},
"avewind": {
"mph": 11,
"kph": 18,
"dir": "W",
"degrees": 260
},
"avehumidity": 48,
"maxhumidity": 0,
"minhumidity": 0
}
I am able to get the "date", "high" and "low" Strings, but I'm unable to get the "conditions" and I don't understand what I'm doing wrong.
I am getting the following exception:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON
As far as I understand the JSON is not malformed. How am I supposed to get the "conditions" value?
I've tried other JSON parsers / libraries as well, but nothing worked out. I'd like to continue working with the Gson-Library, and I guess I'm quite close, but stuck.
Thanks for any help.
If you break down the line that's throwing the exception you can see that you are actually trying to parse as JSON a string that is in fact not JSON.
try {
JsonObject jo = forecastJson.getAsJsonObject();
JsonElement je = jo.get("conditions");
String s1 = je.getAsString();
// at this point s1 contains the value "Partly Cloudy" which you
// are trying to parse as JSON.
JsonElement je2 = jp.parse(s1);
conditions = String.valueOf(je2);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
As "JB Nizet" pointed out in the comment under my question, I was trying to parse the JSON every time again when I wanted to get another piece of its contents. That was my (beginner) mistake.
Now I parse only once and then get the contents directly, without any problem:
JsonParser jp = new JsonParser();
JsonElement forecastJson = jp.parse(new InputStreamReader((InputStream) connection.getContent())).getAsJsonObject()
.getAsJsonObject().get("forecast")
.getAsJsonObject().get("simpleforecast")
.getAsJsonObject().getAsJsonArray("forecastday").get(1);
String date = forecastJson.getAsJsonObject().get("date")
.getAsJsonObject().get("epoch").getAsString();
String high = forecastJson.getAsJsonObject().get("high")
.getAsJsonObject().get("celsius").getAsString();
String low = forecastJson.getAsJsonObject().get("low")
.getAsJsonObject().get("celsius").getAsString();
String conditions = forecastJson.getAsJsonObject()
.get("conditions").getAsString();
First of all, as they say in the comments there's really no need to parse every piece again.
String date = String.valueOf(jp.parse(forecastJson
.getAsJsonObject().get("date")
.getAsJsonObject().get("epoch").getAsString()));
Is the same as:
String date = forecastJson.getAsJsonObject().get("date")
.getAsJsonObject().get("epoch").getAsString();
The problem that you're experiencing is actually something that I suspect is a bug in the Gson library. When it tries to parse a string with spaces in it, it will tokenize that string and expect that after the first word (Partly in this case) the document should end and that the json is malformed since it hasn't reached the end of the document.
So to solve this, either do as the comments say, which is the reasonable thing in your case. Or if you wan't you could always change Partly cloudy to for example Partly_cloudy and it will work :)

create dummy SearchResponse instance for ElasticSearch test case

I'm trying to create a dummy SearchResponse object by passing the values manually to the constructor. I have a JUnit test class for which I'm using this dummy value to mock the actual method call. Trying with the below method to
public SearchResponse actionGet() throws ElasticsearchException {
ShardSearchFailure[] shardFailures = new ShardSearchFailure[0];
int docId = 0;
String id = "5YmRf-6OTvelt29V5dphmw";
Map<String, SearchHitField> fields = null;
InternalSearchHit internalSearchHit = new InternalSearchHit(docId, id,
null, fields);
InternalSearchHit[] internalSearchHit1 = { internalSearchHit };
InternalSearchResponse EMPTY = new InternalSearchResponse(
new InternalSearchHits(internalSearchHit1, 0, 0), null, null,
null, false);
SearchResponse searchResponse = new SearchResponse(EMPTY, "scrollId",
1, 1, 1000, shardFailures);
return searchResponse;
}
and here is my actual value of json when query directly to elasticsearch.
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"failed": 0
},
"hits": {
"total": 28,
"max_score": null,
"hits": [
{
"_index": "monitoring",
"_type": "quota-management",
"_id": "5YmRf-6OTvelt29V5dphmw",
"_score": null,
"_source": {
"#timestamp": "2014-08-20T15:43:20.762Z",
"category_name": "cat1111",
"alert_message": "the new cpu threshold has been reached 80%",
"alert_type": "Critical",
"view_mode": "unread"
},
"sort": [
1408549226173
]
}
]
}
}
I want to create similar kind of response by creating the actual SearchResponse Object. But I couldn't find any way to send the values in InternalSearchHit[]. Please let me know how can I do this.
This will do what you want:
SearchShardTarget shardTarget = new SearchShardTarget("1", "monitoring", 1);
ShardSearchFailure[] shardFailures = new ShardSearchFailure[0];
float score = 0.2345f;
BytesReference source = new BytesArray("{\"#timestamp\":\"2014-08-20T15:43:20.762Z\",\"category_name\""
+ ":\"cat1111\",\"alert_message\":\"the new cpu threshold has been reached 80%\",\"alert_type\":"
+ "\"Critical\",\"view_mode\":\"unread\"}");
InternalSearchHit hit = new InternalSearchHit(1, "5YmRf-6OTvelt29V5dphmw", new StringText("quota-management"),
null);
hit.shardTarget(shardTarget);
hit.sourceRef(source);
hit.score(score);
InternalSearchHit[] hits = new InternalSearchHit[]{hit};
InternalSearchHits internalSearchHits = new InternalSearchHits(hits, 28, score);
InternalSearchResponse internalSearchResponse = new InternalSearchResponse(internalSearchHits, null, null,
null, false);
SearchResponse searchResponse = new SearchResponse(internalSearchResponse, "scrollId", 1, 1, 1000,
shardFailures);
If you call toString() on searchResponse it returns:
{
"_scroll_id" : "scrollId",
"took" : 1000,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"hits" : {
"total" : 28,
"max_score" : 0.2345,
"hits" : [ {
"_index" : "monitoring",
"_type" : "quota-management",
"_id" : "5YmRf-6OTvelt29V5dphmw",
"_score" : 0.2345,
"_source":{"#timestamp":"2014-08-20T15:43:20.762Z","category_name":"cat1111","alert_message":"the new cpu threshold has been reached 80%","alert_type":"Critical","view_mode":"unread"}
} ]
}
}
It works for me in ElasticsearchS 6.5
BytesReference source = new BytesArray(
"{your json response come here}" );
SearchHit hit = new SearchHit( 1 );
hit.sourceRef( source );
SearchHits hits = new SearchHits( new SearchHit[] { hit }, 5, 10 );
SearchResponseSections searchResponseSections = new SearchResponseSections( hits, null, null, false, null, null, 5 );
SearchResponse searchResponse = new SearchResponse( searchResponseSections, null, 8, 8, 0, 8, new ShardSearchFailure[] {} );
return searchResponse;

Categories

Resources