Create json fromat in android - android

How can I create a in android json like this.I can create the json object but still facing some problem to make like this.
{
"IncidentDetails": {
"StreetId": "370","StartDate":"21-03-2015","EndDate":"24-03-2015",
"ImageDetails": [
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
},
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
},
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
}
]}
}
What I tried in my android code just have a look it giving totally different output
JSONArray jsonArray = new JSONArray();
JSONObject IncidentDetails = new JSONObject();
try
{
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
jsonArray.put(IncidentDetails);
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj.put("IncidentDetails", jsonArray);
String jsonStr = IncidentDetailsObj.toString();
My current output
{"IncidentDetails":[{"StreetId":"370","StartDate":"18-03-2015","EndDate":""},{"PhoneImageUrl":"\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150318_171451_1389057690.jpg","Base64ImageData":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P\/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P\/wAA"},{"PhoneImageUrl":"\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150318_171451_1389057690.jpg","Base64ImageData":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P\/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P\/wAA"}]}

Use this
JSONArray jsonArray = new JSONArray();
JSONObject IncidentDetails = new JSONObject();
try
{
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
IncidentDetails.put("ImageDetails", jsonArray);
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj.put("IncidentDetails", IncidentDetails);
String jsonStr = IncidentDetailsObj.toString();

see answer with comments,
//* IncidentalDetial is an object not an array
JSONObject IncidentDetails = new JSONObject();
//* add the first three elements
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
//* contruct the imagedetails array
JSONArray jsonArray = new JSONArray();
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
//* add the imagedetails array to the incidentDetials object
IncidentDetails.put(jsonArray);
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj .put(IncidentDetails);
String jsonStr = IncidentDetailsObj.toString();

Notice that that this is very common scenario, so there has to be some library that deals it for you :)
I recommend https://code.google.com/p/google-gson - GSON. All you have to do is to prepare POJO class that describes JSON, in your case:
public class IncidentDetails {
IncidentDetails incidentDetails;
}
public class IncidentDetails {
String streetId;
String startDate;
String endDate;
ImageDetails imageDetails;
}
Then do the same with ImageDetails. All you have to do then is to create GSON with proper naming policy (it converts automaticcaly class fields names to JSON).
gson.toJson(incidentDetails) creates String you desire. gson.fromString(String json) will create IncidentDetails object from json string.

Related

Android JSON Parse

I have this json response:
[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]
I need to parse it on android.
I have trying follow code:
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("");
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));
But it doesnt work.
If my result will be:
{ "data":[{"id":"1","cat":"A","pic":"false","sector":"1"},{"id":"2","cat":"B","pic":"true","sector":"2"}]}
And I modify the code in:
JSONArray jsonArray = obj.getJSONArray("data");
It works.
How Can I parse It considered my first json response (without "data")
Thank you.
You should use next code:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.d("ID -> ", jsonObject.getString("id"));
Log.d("CAT -> ", jsonObject.getString("cat"));
Because you have not an object in json, but an array, so you should create array instead of object. And thats why your modification works. Because in modified code "data" is an object (JSONObject)
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
pic = row.getString("pic");
}
Or you can just use Gson Library. Just create your pojo classes
public class Data{
int id;
String cat;
String pic;
String sector;
//setter and getter
}
then,
List<Data> datas = gson.fromJson(string_of_json_array, new TypeToken<List<Data>>(){}.getType());
for(Data item: datas){
String pic = item.getPic();
}

Read Json in android

{"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true}
How can i read all the keys in the json and how can count all the data in the Jsonarray
My code-->
String members = s;
/* s contain {"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true} */
JSONArray jsonChildArr = new JSONArray(members);
Log.e("Error","Data in jsonArray--->"+jsonChildArr.length());
Simple Way to Read JSON Object
JSONObject jsonObject = new JSONObject(members);
Log.i("Data","Data in jsonObject--->"+jsonObject.getBoolean("721xxxxxxx"));
Do Like this.
try {
String members = s;
/* s contain {"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true} */
JSONObject obj = new JSONObject(members);
JSONArray array = obj.names();
Log.d("ItemCount",array.length()+"");
for(int i=0;i<array.length();i++){
Log.d("Item",array.getString(i)+":"+ obj.getBoolean(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
JSONObject jsonObject = new JSONObject(result);
boolean data = jsonObject .getBoolean("721xxxxxxx");
Log.d("Data","data:"+data );
try this:
String jsonStr = "{"721xxxxxxx":true,"722xxxxxxx":true,"723xxxxxxx":true}";
JSONObject itemJsonObj = new JSONObject(jsonStr );
HashMap<String,Boolean> result = new HashMap<>();
while(itemJsonObj.keys().hasNext()){
//parse json and save as key-value.
result.put(itemJsonObj.keys().next()+"",itemJsonObj.get(itemJsonObj.keys().next());
// result.size() is like array's size.
}
I wrote a library for parsing and generating JSON in Android http://github.com/amirdew/JSON
for your sample:
JSON jsonData = new JSON(jsonString);
int count = jsonData.count();

Retrieving Data with JSON in Android

My application connects to the web and retrieves a JSON file. I am having some issues retrieving the data that I need from this file. Here is the link to the JSON file: http://api.wunderground.com/api/f9d9bc3cc3834375/forecast/q/CA/San_Francisco.json
Here is a snippet of what it looks like:
I would like to get the value of the "period" variable in the first JSon object within the "forecastday" array, which should be 0. Here is how i'm looking at this. "forecastday" is the array, within that there are a number of JSon objects, each containing variables like "period","icon"....."pop".
In my code, I attempt to get the JSON array "forecastday" and then get the first Json object of the array, I then retrieve the value of "period" in that object and set it in a TextView:
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray contacts = jsonObj.getJSONArray("forecastday");
JSONObject c = contacts.getJSONObject(0);
String period = c.getString("period");
responseView.setText(period);
} catch (JSONException e) {
e.printStackTrace();
}
}
When I run the code, nothing is being retrieved. I'm new to working with JSon and am wondering if I'm looking at this wrong. Please help.
Your "forecastday" JSONArray is inside the "txt_forecast" JSONObject that is inside the "forecast" JSONObject of your response, so you have to extract your JSONArray from this JSONObject and not from the root JSON response :
try {
JSONObject jsonObj = new JSONObject(response);
--> JSONObject forecatsObj = jsonObj.getJSONObject("forecast");
--> JSONObject txtForecatsObj = forecatsObj.getJSONObject("txt_forecast");
JSONArray contacts = txtForecatsObj.getJSONArray("forecastday");
...
You were close but it is incorrect, try like this:
JSONObject jsonObj = new JSONObject(response);
JSONObject forecast = jsonObj.getJSONObject("forecast");
JSONObject txtForecast = forecast.getJSONObject("txt_forecast");
JSONArray forecastDay = txtForecast.getJSONArray("forecastday");
//parse the first period value
String period = forecastDay.getJSONObject(0).getString("period");
responseView.setText(period);
Try this code :
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject forecastObj = jsonObj.getJSONObject("forecast");
JSONObject txt_forecastObj = forecastObj.getJSONObject("txt_forecast");
JSONArray foracastdayArray = txt_forecastObj.getJSONArray("foracastday");
JSONObject oOjb0 = foracastdayArray.getJSONObject(0);
String period = oOjb0.getString("perioed");
}catch (Exception e){
}
This code works for me fine:
JSONObject jsonResponse = new JSONObject(responce);
JSONArray jsonMainNode = jsonResponse.optJSONArray("forecastday");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String period = jsonChildNode.optString("period");
responceView.setText(period);
}

Parse list inside a json in android

I am putting a list in the json and now I want to get the list and display each entry in different textview. This is my code to put the list in json and to get the same
static ArrayList<String> list = new ArrayList<String>();
JSONObject json = jsonFruitArray.getJSONObject(i);
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku",new JSONArray(list));
This is how i am trying to get the list
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
You should try like this. Use JsonArray
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("1", 1);
jsonObject.put("2", 2);
jsonObject.put("3", 3);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray result = new JSONArray();
result.put(jsonObject);
//Use json array
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("John");
jsonArray.put("Mat");
jsonArray.put("Jason");
jsonObj.put("json_array", jsonArray);
//Retrieve like this
JSONArray jsonFruitSkuArray = jsonObj.getJSONArray("json_array");
for(int iSku=0; iSku< jsonFruitSkuArray.length();iSku++){
JSONObject jsonSkuObject = jsonFruitSkuArray.getJSONObject(iSku);
productBean.setSkuId1(jsonSkuObject.getInt("sku"));
}
In your code you can try following :
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject();
list.add("john");
list.add("mat");
list.add("jason");
json.put("sku", new JSONArray(list));
JSONArray jsonFruitSkuArray = json.getJSONArray("sku");
for (int iSku = 0; iSku < jsonFruitSkuArray.length(); iSku++) {
String element = jsonFruitSkuArray.getString(iSku);
System.out.println(element);
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources