How to put data into nested array? - android

I am new to android so I need help.
From card-view I will get (Test-name,Test-date,Test-time). different test-name will have different test-date and test-time(Sample format given below)
I want to save the data and send it in the given sample format when I clicked the button. I am not able to find a way how to write a code to save my data in such format. I have researched a bit, I found that it can be done through nested array(maybe I am wrong) I am not sure. Can anyone provide a sample code how can I save the data in such format?
{
"testDetails": [{
"Testname": "abc",
"TestDate": "2018 - 02 - 01",
"TestTime": "18: 00: 00"
},
{
"Testname": "def",
"TestDate": "2018 - 03 - 01",
"TestTime": "18: 50: 00"
},
{
"Testname": "ghi",
"TestDate": "2018 - 04 - 11",
"TestTime": "06: 43: 37"
}
]}
Note: This sample is created by me manually so that you can get an idea of how I want the data to appear after saving.

Put this is some for loop:
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("TestName", "abc");
item.put("TestDate", "2018 - 02 - 01");
item.put("TestTime", "18: 00: 00");
array.put(item);
json.put("testDetails", array);

Related

Parsing JSON from nested result android

Here is my code:
try{
JSONObject jsonObjitem = new JSONObject(jsonString);
JSONArray phrasemaster = jsonObjitem.getJSONArray("phrases");
for(int i = 0; i<phrasemaster.length();i++){
JSONObject scan = phrasemaster.getJSONObject(i);
int id = scan.getInt("id");
if (id == current){
String question = scan.getString("question");
idoutcome1 = scan.getString("idoutcome1");
idoutcome2 = scan.getString("idoutcome2");
idoutcome3 = scan.getString("idoutcome3");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The user on launch gets random number, when he press the button he is being moved to another fragment where this number is used to pull item from JSON, this number serves as id.
Each item have another three id's. So when I pull my item with this code I also pull 3 id's from that json item. Now what I want is to output the question string from these id's.
{
"phrases": [
{
"id": 1,
"question": "first item",
"idoutcome1": 2,
"idoutcome2": 3,
"idoutcome3": 4
},
{
"id": 2,
"nameofoption": "item 2",
"question": "some question 2",
"idoutcome1": 5,
"idoutcome2": 6,
"idoutcome3": 7
},
{
"id": 3,
"nameofoption": "item 3",
"question": "some question 3",
"idoutcome1": 8,
"idoutcome2": 9,
"idoutcome3": 10
}
]
}
The thing is that I don't understand how I can reach out to these values.
Edit: illustration of what I'm trying to do.
While parsing I take the idoutcome1,2,3 values and output them on my buttons.
However, I want to output the value written in the nameofoption field instead of these numbers. Just like the example, instead of 2 it should show "left".
The problem is that I have this try that searches for id that it got on the previous page and outputs item with corresponding id. How can I implement it within the course of this try that it would go deeper and depending on the idoutcome's of this JSON item display values from the nameofoption field?
I've solved it in a following way, all of the idoutcome's were put in arraylist, then I've reused the same json parsing code to loop through the items with the respective id's and then output them ti the buttons with settext.
That was my first json experience, thanks for the downvotes.

Parse JSON with optional field

I'm trying to parse in android studio a JSON, that containts this :
"stops":
[
{
"num": 1,
"time": "2016-04-27T06:15:00.000Z",
"title":"Flight to London",
"desc":"Barcelona BCN-London-Gatwick LGW",
"type":"0",
"subtype":0
},
{
"num": 2,
"time": "2016-04-27T10:35:00.000Z",
"title":"Gatwick express",
"desc":"From Airport to London",
"type":"0",
"subtype":1
},
{
"num": 3,
"time": "2016-04-27T12:15:00.000Z",
"title":"Pub the black horse",
"desc":"From Airport to London",
"type":1,
"subtype":1,
"location": "51.476334, -0.062700",
"images": [ "https://fitzrovianews.files.wordpress.com/2011/01/black_horse_rathbone_pl.jpg"
]
},
{
"num": 4,
"time": "2016-04-27T12:16:47.000Z",
"title":"The Tower Bridge",
"desc":"# The Tower Bridge Facts\n## Architecture\n**Tower Bridge** is a combined bascule and suspension bridge in London built in _1886–1894_. The bridge crosses the River Thames close to the Tower of London and has become an iconic symbol of London. Tower Bridge is one of five London bridges now owned and maintained by the Bridge House Estates, a charitable trust overseen by the City of London Corporation. \n>It is the only one of the Trust's bridges not to connect the City of London directly to the Southwark bank, as its northern landfall is in Tower Hamlets.\n## The bridge Exhibition\nThis must-see London attraction invites you to step inside the most famous bridge in the world to explore its iconic structure, spectacular views and glass floor, modern exhibitions and magnificent Victorian Engine Rooms! ",
"type":1,
"subtype":6,
"location": "51.507792, -0.087786",
"images": [
"https://i.ytimg.com/vi/nby0Mr2LfBQ/hqdefault.jpg",
"http://raindropsofsapphire.com/wp-content/uploads/2011/10/london-bridge.jpg",
"http://www.londonforfree.net/gizmo/wp-content/uploads/2015/02/southwark-bridge.jpg"
]
},
{
"num": 5,
"time": "2016-04-27T12:18:10.000Z",
"title":"St. Paul Cathedral",
"desc":"# HISTORY \nSt **Paul's Cathedral**, London, is an _Anglican cathedral_, the seat of the _Bishop of London_ and the mother church of the Diocese of London. \n * It sits on Ludgate Hill at the highest point of the City of London and is a Grade 1 listed building. \n * Its dedication to Paul the Apostle dates back to the original church on this site, founded in AD 604.",
"type":1,
"subtype":6,
"location": "51.513825, -0.098351",
"images": [
"https://d1wgio6yfhqlw1.cloudfront.net/sysimages/product/resized6/Interior_St_Pauls_Cathedral_132_12992.jpg",
"https://d1kioxk2jrdjp.cloudfront.net/resized/486x324/48-st_pauls_ctahedral_millenirm_bridge.jpg",
"http://i4.mirror.co.uk/incoming/article8299330.ece/ALTERNATES/s615b/LOND-2016-052-HMQ-St-Pauls-Thanks-Giving-704JPG.jpg"
]
}
]
The problem is, i don't know how to deal with the field "location" or "images" which are optional. I know how to deal with the first "stop", i'm doing this :
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
......
}
But i don't know how to check it here is a elment location or a jsonArray "images"...
best way to handle optional fields in JSON is to use opt instead of get
opt provides the parsed value if exist or default value for that datatype if requested key does not exist.
best thing is, it don't even need a try catch block since it always returns a value and in case of any error from server, it will not let your app crash or prevent other values from being parsed.
String location = response.optString("location");
if location exist in response, then it will initialize with the value or it will leave the string null. in case of int or long default is 0, in case of boolean default is false. read about opt for more details.
Use has() method
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
if(c.has("location") && !c.isNull("location")){
// parse location
}
if(c.has("images") && !c.isNull("images")){
// parse images
}
.....
}
you should use Retrofit and Google Gson, where you do not have to do lot of work,
they will do the job for you.
look at these
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.vogella.com/tutorials/Retrofit/article.html

How to fix inaccurate DateTime (minutes) parsed with Jackson/Gson libraries?

I am developping an Android application that dialogs with some Google App Engine web-services.
This application implements a Chat Activity which have very a very simple feature: send text.
During debugging I noticed that the messages I was listing from the server were not displayed in the same order I had sent them on my application. My first thought was that the problem was comming from the server.
At first I checked the raw Json I was receiving:
{
"messages": [
{
"message": "test 3",
"author": "daniel",
"message_id": "5724160613416960",
"sent_at": "2014-11-13T09:42:42.861950"
},
{
"message": "test 2",
"author": "daniel",
"message_id": "5649050225344512",
"sent_at": "2014-11-13T09:42:10.390960"
},
{
"message": "test 1",
"author": "daniel",
"message_id": "5178081291534336",
"sent_at": "2014-11-13T09:41:01.998830"
}
],
"kind": "company#chatsItem",
"etag": "\"RUCkC9XynEQNZ2t5E0aa41edXro/xRNtgkWIUbq4zCgmv2iq2fy-UIg\""
}
As you can see, the raw data is correctly ordered. But here comes the funny part. When I add a JSON parser, such as JacksonFactory (or even GsonFactory):
Company.Builder builder = new Company.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
Company service = builder.build();
ChatsChatCollectionResponse response = service.chats().list(user_id, album_id, token).execute();
List<ChatsChatResponse> messagesResponse = response.getMessages();
Here are the ChatsChatResponse items ordered in the same way as above:
[0] = {com.appspot.com_pany.company.model.ChatsChatResponse#830029063096} size = 4
[0] = {com.google.api.client.util.DataMap$Entry#830029082528}"author" -> "daniel"
[1] = {com.google.api.client.util.DataMap$Entry#830029082552}"message" -> "test 3"
[2] = {com.google.api.client.util.DataMap$Entry#830029082576}"message_id" -> "5724160613416960"
[3] = {com.google.api.client.util.DataMap$Entry#830029082600}"sent_at" -> "2014-11-13T10:57:03.950+01:00"
[1] = {com.appspot.com_pany.company.model.ChatsChatResponse#830029066376} size = 4
[0] = {com.google.api.client.util.DataMap$Entry#830029083616}"author" -> "daniel"
[1] = {com.google.api.client.util.DataMap$Entry#830029083640}"message" -> "test 2"
[2] = {com.google.api.client.util.DataMap$Entry#830029083664}"message_id" -> "5649050225344512"
[3] = {com.google.api.client.util.DataMap$Entry#830029083688}"sent_at" -> "2014-11-13T10:48:40.960+01:00"
[2] = {com.appspot.com_pany.company.model.ChatsChatResponse#830029068008} size = 4
[0] = {com.google.api.client.util.DataMap$Entry#830029084760}"author" -> "daniel"
[1] = {com.google.api.client.util.DataMap$Entry#830029084784}"message" -> "test 1"
[2] = {com.google.api.client.util.DataMap$Entry#830029084808}"message_id" -> "5178081291534336"
[3] = {com.google.api.client.util.DataMap$Entry#830029084832}"sent_at" -> "2014-11-13T10:57:39.830+01:00"
Why is there such a random difference on the "sent_at" field ?
EDIT
I forgot to mention that I am not talking about the 1 hour shift that corresponds to TimeZone, but rather on how random the minutes are.
I'm not sure about the solution, but the explanation seems quite clear: the variation is not random at all, but rather caused by adding everything after the decimal point as milliseconds.
Take the third entry, for example:
2014-11-13T09:41:01.998830
Evidently, the parser reads this as:
hours: 09
minutes: 41
seconds: 01
milliseconds: 998830
Since milliseconds is greater than 1000, it ends up being transformed into 998s 830ms, which when accounting for full minutes is 16m 38s 830ms. Hence:
hours: 09
minutes: 41 + 16
seconds: 01 + 38
milliseconds: 830
Which produces exactly the result you're seeing (modulo timezone adjustment):
2014-11-13T10:57:39.830+01:00
If you have control over the service output (this point is not quite clear from the question wording), the easiest fix would be to output only three digits after the decimal points (i.e. rounding at milliseconds instead of millionths). For the example, this would be 2014-11-13T09:41:01.999.
It might also be possible to fix this on the parser itself, but it would require a bit more research (and ideally, a gist that reproduces the problem).
try setting a custom date format like
Gson gson = new
GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
As #matiash noted, you have a non-standard date format that contains microseconds. The problem is that SimpleDateFormat, used by Jackson, incorrectly parses microseconds.
To alleviate this you should create a custom deserializer that truncates the microseconds to milliseconds:
public class MicrosecondDateSerializer extends JsonDeserializer<Date> {
private static SimpleDateFormat formatter =
new SimpleDateFormat("dd-MM-yyyyThh:mm:ss:SSS");
#Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = jp.getCodec().readTree(jp);
String dateString = node.get("sent_at").asText();
String dateStringTruncated = dateString.substring(0, dateString.length() - 3);
return formatter.parse(dateStringTruncated);
}
}

json parsing without name in android

i have worked with json name value pair before works fine and great but below is my json object in which there is no name and only value. Can anyone tell is it possible to use this type of json in android if yes then how to extract values from this json object. or any related link will be great.
JSON OBJECT
{
"log_list": [
[
"21",
"doctorFisher",
"Pharmacy 1",
"patientfish",
"test",
"2014-08-25 05:58:18",
"record UCI tech FDNY icky shut rack soon sun TDK tell. ox it'll ohm URL did GCVO dash ugly dog did flood idiot fluff if if rid t-shirts didn't TechTV only chef doc scotch Rebekah an if lb tax scotch am ICN JCB JCB HGV JCB HGV in on pm tax UDC OK red uh HK ohm",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"3c59dc048e8850243be8079a5c74d079\") onmouseover=\"this.style.cursor='pointer'\" src=\"\" width=\"20\" height=\"20\">"
],
[
"20",
"doctortest12345",
"Pharmacy 1",
"testpatient12345",
"test",
"2014-08-25 03:57:32",
"she'd Urdu text scuff uno dad uno each ink why tough days ICO saved USCIS David rig though end FDIC UCI's for USCIS tend did for dog such vidi fly floor exited did DND hand bid GMD.",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"98f13708210194c475687be6106a3b84\") onmouseover=\"this.style.cursor='pointer'\" width=\"20\" height=\"20\">"
]
}
thanks in advance
Yes, that format would work and you can pretty easily use it.
Assuming you have a variable String json which contains that data:
JSONObject jsonObj = new JSONObject(json);
Now log_list would be parsed as a JSONArray like so:
JSONArray logJsonArray = jsonObj.getJSONArray("log_list");
Then you can iterate through that outer array very similar to how you would a normal array or ArrayList:
for(int outerArrayPos = 0; outerArrayPos < logJsonArray.length(); outerArrayPos++){
JSONArray innerArray = logJsonArray.getJSONArray(outerArrayPos);
for(int innerArrayPos = 0; innerArrayPos < innerArray.length(); innerArrayPos++){
String valueAtIndex = innerArray.getString(innerArrayPos); //innerArray
// Do whatever you want with the values here
}
}
That will parse your String, but figuring out how to actually use that data is going to be most of your struggle, so I hope the order in which the information is returned will always be the same for your sake.
If you can, I would definitely recommend using a JSONObject for the data that is currently contained in your inner array. e.g.
{
"log_list": [
{
"id": "21",
"name": "doctorFisher",
.....
}
]
}

org.json.JSONException: Expected literal value at character 550 of

I am trying to read JSON file from asset folder. But I get the following exception
org.json.JSONException: Expected literal value at character 550
I searched lot of stuff but didn't find anything relative. Here is my JSON file.
I find JSON object on 550 is "names": ["Santosh","Sandip","Arvind"],. I am trying to solve it but don't know what happens in my code.
Here is my code.
I also debug my code but when control goes on JSONObject jsonObject = new JSONObject(text); it throw exception and goes in first catch block.
Please give me any reference or hint to solve this problem.
Any help appreciated.
your JSON is invalid.your JSON should look like this
{
"resultCount": 3,
"SearchedTerm": "Wada Pav",
"results": [
{
"locationname": "Mahableshwar Hotel",
"locationid": "12345",
"locationaddress": "baner, Pune",
"dishrating": "4",
"dishname": "Wada Pav",
"dishid": "234",
"dishcategory": "Snacks",
"dishnotes": "Spicy Wada Pav",
"dishpreviewurl": "http://xxx.yyy.zzz/mahableshwar/1.jpg",
"dishtotalvotes": "9999",
"friendslistvoted": {
"friendscount": "3",
"names": [
"Santosh",
"Sandip",
"Arvind"
]
},
"dishimageurl": "http://xxx.yyy.zzz/mahableshwar/2.jpg",
"mylastrating": "4"
}
]
}
try using a JSON validator before using it (like JSLint).
I'm using following to get standard JSON format.
This one is better.
public static String convertStandardJSONString(String data_json) {
data_json = data_json.replaceAll("\\\\r\\\\n", "");
data_json = data_json.replace("\"{", "{");
data_json = data_json.replace("}\",", "},");
data_json = data_json.replace("}\"", "}");
return data_json;
}
I use jsoneditoronline online tool that works pretty good.
this works for me
public static String convertJSONString(String data) {
data = data.replace("\\", "");
return data; }

Categories

Resources