I have some data which I want to convert into json object. The data I want is like
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
The weekday is of array type and others are json object type. I have done some code to convert it but I am able to convert it like
{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
Code for this :
Code for creating weekdata array :
String firstDay = etDate1.getText().toString() + "##" + etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" + etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
Conversion into json to send it into volley :
HashMap<String, String> params = new HashMap<String, String>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata.toString() );
JSONObject obj = new JSONObject(params);
And I get data like :
{"weekdata":"[\"2019-04-01##5:0##5:0\",\"2019-04-02##5:0##5:0\"]","package_id":"44","week":"Apr 01, 2019"}
How can I convert it like below format:
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
Please help.
This is happening because you have defined your Map as Map and converting your list to String using toString() method. Which is generating your String with . You should define your Map as Map and don't use the toString method while putting it into the Map.
Code:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("package_id", package_id);
params.put("week", weekName);
params.put("weekdata",weekdata);
JSONObject obj = new JSONObject(params);
One question here is why are you using Map? is there is any special reason for that?
You can create JSON directly from JSONObject.
Sample Code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
With JSONObject you don't have to worry about generics.
As per your question,
How can I convert it like below format:
{"week":"Apr 22, 2019","package_id":23,"weekdata":["2019-05-07##14:00##16:45"]}
String firstDay = etDate1.getText().toString() + "##" +
etStartTime1.getText().toString() + "##" + etEndTime1.getText().toString();
String secondDay = etDate2.getText().toString() + "##" +
etStartTime2.getText().toString() + "##" + etEndTime2.getText().toString();
selectionItems.add(firstDay);
selectionItems.add(secondDay);
String[] blist = new String[selectionItems.size()];
Log.e("tag", "array" + blist.length + selectionItems);
for (int i = 0; i < selectionItems.size(); i++) {
blist[i] = selectionItems.get(i);
}
Log.e("tag", "arrayList" + blist[0]);
JsonArray weekdata = new JSONArray();
for (int i = 0; i < blist.length; i++) {
weekdata.put( blist[i] );
}
After this wrap this in the JsonObject
JsonObject jsonObject = new JsonObject();
jsonObject.put("package_id", package_id);
jsonObject.put("week", weekName);
jsonObject.put("weekdata",weekdata);
Log.e("jsonResult",jsonObject.toString());
Try this and let me know #mishti.
Related
I am trying to send an array with a bunch of objects back to android?
I tried String Builder like so:
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{userId:" + userChange.getUserId() + ",";
String followingStr = "following:" + String.valueOf(userChange.getIsFollowingType())+ "}]";
sb.append(userIdStr).append(followingStr);
but I am doing something wrong here. On my server side I am using node.js and would parse the array if I send over a string no problem, but this is not sending a string version of the array? What do I need to change on my string builder? Or is there a more efficient way to send over the list of usersChanged - (which is List)
I am using retrofit if there is a way to do it easy with that.
Your code will send things like
[{userId: someuserid, following: someparameter}]
You need to have the double quote (" ") sent over as well.
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{\"userId\":\"" + userChange.getUserId() + "\",";
String followingStr = "\"following\":\"" + String.valueOf(userChange.getIsFollowingType())+ "\"}]";
sb.append(userIdStr).append(followingStr);
You should also probably move the "]" to after the loop.
EDIT:
Forgot to mention this, but you can definitely use JSONArray and JSONObject to make your life easier.
JSONArray jsonArray = new JSONArray();
for(...){
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userChange.getUserId());
jsonObject.put("following", String.valueOf(userChange.getIsFollowingType()));
jsonArray.put(jsonObject);
}
Then send over the jsonArray.
I want to load JSON data into the List view with subtitle and images (Left side on the row).
Here below I have posted my sample JSON response code :
for (int i = 0; i < contacts.length(); i++) {
JSONObject obj = contacts.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
Log.d("Response: ", "> " + currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//Log.d("Response: ", "> " + name);
//store name in an arraylist
}
}
}
}
I want to Show Tittle : currentDynamicKey values and Sub Title : Name string values.
If you already have your data and you don't necessarily need to integrate the server requests with your adapter, then you really just need an adapter which supports a JSONArray. There's a really nice open source one within the Advanced-Adapters library. Then it's just a matter of passing the JSONArray to the adapter and setting the adapter to a ListView.
i use www.openweathermap.org FORECAST.
thisi the result of forecat: http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139
JSONObject coordObj = getObject("coord", jObj);
Latitude=getFloat("lat", coordObj);
Longitude=getFloat("lon", coordObj);
JSONObject coordObj = getObject("city", jObj);
id=getFloat("id", coordObj);
name=getFString("name", coordObj);
JSONObject sysObj = getObject("sys", jObj);
Country=getString("country", sysObj);
Sunrise=getInt("sunrise", sysObj));
Sunset=getInt("sunset", sysObj));
JSONObject jlist = jObj.getObject("list");
JSONObject JSONWeather = jArr.getJSONObject(0);
Condition_id==getInt("id", JSONWeather);
condition_description=getString("description", JSONWeather);
condition=getString("main", JSONWeather);
condition_icongetString("icon", JSONWeather);
JSONObject mainObj = getObject("main", jObj);
Humidity=getInt("humidity", mainObj);
Pressure=getInt("pressure", mainObj);
MaxTemp=getFloat("temp_max", mainObj);
MinTemp(getFloat("temp_min", mainObj);
Temp=getFloat("temp", mainObj);
// Wind
JSONObject wObj = getObject("wind", jObj;
Speed=getFloat("speed", wObj);
Deg=getFloat("deg", wObj);
// Clouds
JSONObject cObj = getObject("clouds", jObj);
Perc=getInt("all", cObj);
please how to loop the weather array ?
First, list is not a JsonObject it's an array, so you should get it doing:
JSONArray jlist = (JSONArray) jObj.get("list");
Depending of which library you are using the syntax can change but the logic is the same, I'm explaining using json simple lib.
after that you should iterate your list array, something like this:
for (int i = 0; i < jlist.size(); i++){
// get all your objects and your weather array
// to get your weather array the logic is the same:
JSONArray jArrayWeather = (JSONArray) jObj.get("weather");
for (int j = 0; j < jArrayWeather ; j++){
//and here you can get your id, main, description and icon using j index
JSONObject currentObj = (JSONObject) jArrayWeather.get(j);
String main = (String) currentObj.get("main");
}
}
I didn't test this code, so follow the idea and try to do it yourself. Take a look here as we can see you haven't experience with json
Here is another example. (For a different JSON format though).
try{
JSONArray list=json.getJSONArray("list");
for(int indx=0;indx<MAX_FORCAST_FRAGMENT;indx++) {
JSONArray weather = list.getJSONObject(indx).getJSONArray("weather");
String weatherIconString=setWeatherIcon(weather.getJSONObject(0).getInt("id"),
0,100);
forcastData[indx][0]=weatherIconString;
JSONObject main=list.getJSONObject(indx).getJSONObject("main");
JSONObject wind=list.getJSONObject(indx).getJSONObject("wind");
String detailsFieldString= weather.getJSONObject(0).getString("description").toUpperCase(Locale.US);
String humidityFieldString="Humidity: " + main.getString("humidity") + "%";
String windFieldString= "Wind: " + wind.getString("speed") + " Km/H";
// populate the list view//
int forecastFragmentId=getResources().getIdentifier("forcast_layout_" + (indx+1), "id", getPackageName());
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.details_field);
tv.setText(detailsFieldString);
saveData(F_DETAILS+indx,detailsFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.weather_icon);
tv.setText(weatherIconString);
saveData(F_ICON+indx,weatherIconString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.wind_field);
tv.setText(windFieldString);
saveData(F_WIND+indx,windFieldString);
tv=(TextView)findViewById(forecastFragmentId).findViewById(R.id.humidity_field);
tv.setText(humidityFieldString);
saveData(F_HUMIDITY+indx,humidityFieldString);
c = Calendar.getInstance();
int currentDate=c.get(Calendar.DAY_OF_MONTH);
saveTime(LAST_FORCAST_TIME,currentDate);
}
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data in renderForecastData");
}
}
it gives me the error log : " org.json.JSONException: No value for tableData"
try {
JSONObject mainJson22 = new JSONObject(reply);
JSONObject jsonResult = mainJson22.getJSONObject("UserListByBusinessAreaContextResult");
JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");
// JSONArray jsonArray22 = mainJson22.getJSONArray("UserListByBusinessAreaContextResult"); // JSONArray jsonArray22 = jsonResult.getJSONArray("tableData"); Log.i("mainjson234","" + jsonArray22);
for (int i2 = 0; i2 < jsonArray22.length(); i2++) {
JSONObject objJson22 = jsonArray22.getJSONObject(i2);
the error is on line : `"JSONArray jsonArray22 = jsonResult.getJSONArray("tableData");"
heres the json:
{
"UserListByBusinessAreaContextResult": "{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
}
The object UserListByBusinessAreaContextResult contains a string. This string is:
"{\"tableData\":[{\"UserID\":30,\"Username\":\"Teste\",\"Name\":\"Teste\"}]}"
Do you notice the quotes? The problem is, that your WCF service returns a JSON string, not an object. So either you will have to change the WCF service to deliver an object instead, or parse that string again. Like this (not tested):
JSONObject mainJson22 = new JSONObject(reply);
JSONObject tableData = new JSONObject(
mainJson22.getString("UserListByBusinessAreaContextResult"));
I wonder why I can't read the JSON Object like this :
{
"1":{"bulan":"Januari","tahun":"2012","tagihan":"205000","status":"Lunas"},
"2":{"bulan":"Februari","tahun":"2012","tagihan":"180000","status":"Lunas"},
"3":{"bulan":"Maret","tahun":"2012","tagihan":"120000","status":"Lunas"},
"4":{"bulan":"April","tahun":"2012","tagihan":"230000","status":"Lunas"},
"5":{"bulan":"Mei","tahun":"2012","tagihan":"160000","status":"Lunas"},
"6":{"bulan":"Juni","tahun":"2012","tagihan":"150000","status":"Belum Lunas"},
"panjang":6
}
with my android code like this :
try {
int length = jobj.getInt("panjang");
for(int n = 0; n < length; n++){
String m = Integer.toString(n)
JSONObject row = jobj.getJSONObject(m);
String bulan = row.getString("bulan");
String tahun = row.getString("tahun");
String tagihan = row.getString("tagihan");
String status = row.getString("status");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bulan", bulan);
map.put("tahun", tahun);
map.put("tagihan", tagihan);
map.put("status", status);
list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
It always return nothing, but it works fine if I change the key m to specific key like if
String m = "1";
and I can't use
JSONObject row = jobj.getJSONObject(n);
because getJSONObject() just accept string, not int.
is there something wrong with my code?
Your problem lies in the initial iterator value. It failed to search for key "0", because you don't have "0". Change it to:
for(int n = 1; n <= length; n++){
Should fix the problem.