Parsing JSON object using jackson - android

I am usin android built in parser but it is very slow. I want to use jackson but i am not able to understand hoe to perform same things with jackson as i did with android built it parser.
here is my code
String data = getArguments().getString("data");
String RECCO_INFO = null;
try {
RECCO_INFO = getReccos(data);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray RECCO_ARRAY = new JSONArray();
try {
RECCO_ARRAY = new JSONArray(RECCO_INFO);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < RECCO_ARRAY.length(); i++) {
try {
JSONObject recco = RECCO_ARRAY.getJSONObject(i);
String program = recco.getString("program");
String outlet = recco.getString("outlet");
String normalized_weight = recco.getString("normalized_weight");
String distance = recco.getString("distance");
HashMap<String, String> map = new HashMap<String, String>();
String program_name = new JSONObject(program).getString("name");
String outlet_basics = new JSONObject(outlet).getString("basics");
String outlet_name = new JSONObject(outlet_basics).getString("name");
map.put("program_name", program_name);
map.put("outlet_name", outlet_name);
map.put("normalized_weight", normalized_weight);
map.put("distance", distance);
oslist.add(map);
list= (ListView) rootView.findViewById(R.id.recco_list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.recco_list_view, new String[] {"program_name","outlet_name", "normalized_weight", "distance"},
new int[]{R.id.program_name,R.id.outlet_name, R.id.normalized_weight, R.id.distance});
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return rootView;
}
public String getReccos (String data) throws JSONException {
JSONObject json = new JSONObject(data);
JSONObject info = json.getJSONObject("info");
JSONObject RECCO = info.getJSONObject("RECCO");
JSONArray RECCO_INFO = RECCO.getJSONArray("info");
return RECCO_INFO.toString(1);
}
Please anybody help me usin jackson, i have already downloaded jars. i have tried it seeing some examples but i am able to fully understand it.

Create Getters and Setters for all the key in json.
Create an instance of ObjectMapper.
Configure the object mappers.
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
pass the response and class.
GetDetails mDetails = objectMapper.readValue(response, GetDetails.class)
Starting getting the values.
Here is a simple example for the OP's JSON. If you can post your JSON, I can post the code to parse and get all values.
Here is one more example.

The main problem here is not the JSON parsing but these lines:
for(....){
list= (ListView) rootView.findViewById(R.id.recco_list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.recco_list_view, new String[] {"program_name","outlet_name", "normalized_weight", "distance"},
new int[]{R.id.program_name,R.id.outlet_name, R.id.normalized_weight, R.id.distance});
list.setAdapter(adapter);
}
They are heavily unoptimised. All of this should be done outside the list, because you are creating/inflating them many many times. If you want the effect that items appear one by one, use adapter.notifyDataSetChanged method. Move them out and you will notice that performance improved many times.

Well answering my own question.
I am using Gson to deserialise json into java POJO. it is quite simple and easy.
This link will help.

Related

Is it possible to send Arraylist as value to a single key in BasicValuePair in android

Hi i have multi dimensional array format data.I need to pass these datas with basicnamevaluepair to POST method.Is there any possible to pass the entire arraylist as value to single key in android.
ex:
the arrayList is
ArrayList<String> data=new ArrayList<String>();
data.add("Datas");
data.add("Datas2");
data.add("Datas3");
Is it possible to pass arraylist like this.Passing values in ArrayList using BasicNameValuePair.
List<BasicNameValuePair> pairedData=new ArrayList<BasicNameValuepair();
pairedDatas.add(new BasicNameValuePair("id","8"));
pairedDatas.add(new BasicNameValuePair("name","Customer Details"));
pairedDatas.add(new BasicNameValuePair("datas",data);
you cant add BasicNameValuePair
List<BasicNameValuePair> pairedData=new ArrayList<BasicNameValuepair();
pairedDatas.add(new BasicNameValuePair("id","8"));
pairedDatas.add(new BasicNameValuePair("name","Customer Details"));
ArrayList<String> data=new ArrayList<String>();
data.add("Datas");
data.add("Datas2");
data.add("Datas3");
// you need to convert tha array to formatted String
JSONArray jsArray = new JSONArray(data);
pairedDatas.add(new BasicNameValuePair("datas",data.toString());
There is no possible to pass arraylist values in basicnamevalue pair.the only thing we can do this.Convert the product array as jsonArray and later convert it as string and pass it as string in basicnamevaluepair.At server side we need to parse string using jsondecode whose key having jsonarray as string .
Download GSON library from hare
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm and
add library in your project lib folder.
try this code
List<storeData> list=new ArrayList<storeData>();
for(int i=1;i<10;i++){
storeData("0"+i);}
private void storeData(String s)
{
storeData objDetails = new storeData(s);
list.add(objDetails);
}
class storeData {
private String strNumber;
public storeData(String l) {
strNumber = l;
}
}
Gson gson = new Gson();
String jsonString = gson.toJson(list); // convert data to json
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("jsonval", jsonString)); // pass data to server
note : parse json data in server side and insert data into table . you can modify this code as per ur requirements .
You can add array list to name value pair as mentioned in the code.Just convert array list to string by .toString() method.
Initialise String builder first.
StringBuilder TaskID= new StringBuilder("");
StringBuilder FFCheckListID= new StringBuilder("");
StringBuilder FFCheckListLineItemSNo= new StringBuilder("");
TaskID.append("taskid");
TaskID.append(",");
FFCheckListID.append("id");
FFCheckListLineItemSNo.append("SNO");
AND ADD STRINGBUILDER TO ARRAYLIST
I was faced with this kind of challenge , I solved my issue with this way.
LinkedList<String> llistobj = new LinkedList<String>();
ArrayList<String> arraylist= new ArrayList<String>();
arraylist.add("material_id");
arraylist.add("1");
arraylist.add("amount");
arraylist.add("10");
arraylist.add("material_id");
arraylist.add("2");
arraylist.add("amount");
arraylist.add("20");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(newBasicNameValuePair("materials_receive",
Arrays.toString(llistobj.toArray())));
You have toi use jsonArray to send arraylist, use this code
JSONObject outerJsonObject ;
JSONArray _mainArray ;
outerJsonObject = new JSONObject();
_mainArray = new JSONArray();
for (int i = 0; i < count; i++) {
JSONObject _jSubObj = new JSONObject();
try {
_jSubObj.put("user_id",_userId);
_jSubObj.put("first_name",name.get(i));
}
_mainArray.put(_jSubObj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
outerJsonObject.put("address_details",_mainArray);
// System.out.println("OuterJSON request"+outerJsonObject);
// System.out.println("JSON ARRAY : " + _mainArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In this code name is arraylist at position of i.
and parameter use like
// Creating HTTP client
client = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(WebServiceConstants
.getMethodUrl(WebServiceConstants.METHOD_ADD_ADDRESS));
// Building post parameters, key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("address_details", outerJsonObject.toString()));
System.out.println("Whole name value pair Address=" + nameValuePair.toString());
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
try {
responseMain = client.execute(httpPost);
// Log.e("RESPONSe of My order", String.valueOf(responseMain));
HttpEntity entitity = responseMain.getEntity();
_responseMain = EntityUtils.toString(entitity); // content will be consume only once
System.out.println("Response of Address "+_responseMain);
} catch (Exception e)
{
e.printStackTrace();
}
I hope it is working

How to create a JSON

I was create a JSON Object like below but i don't know how can fill parameters field with JSONStringer? And parameters field is a JSONArray or Array String?
{"name":"Katy", "parameters":["JAK","1999"], "Age":25}
Thanks for your help .
Try like below
String mParameters[] = { "JAK", "1999" };
JSONObject mJson = new JSONObject();
try {
mJson.put("name", "Katy");
JSONArray mJSONArray = new JSONArray(Arrays.asList(mParameters));
mJson.putOpt("parameters", mJSONArray);
mJson.put("Age", 25);
System.out.println("JSon::"+ mJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
The documentation for JSON will show you that an easy way to distinguish wheter your JSON string is an array is whether it starts with a [, so "parameters" in your example is a JSONArray.
Without knowing how you will be getting the data you want to put in your object, here is an example of how you would populate it (assuming you have an array of JAKS to insert).
JSONObject yourObject = new JSONObject();
String[] JAKS = {"1999", "2000", "2001"};
JSONArray paramaters = new JSONArray();
try {
yourObject.put("name", "Katy");
for (String JAK : JAKS) {
JSONObject yourParamater = new JSONObject();
yourParamater.put("JAK", JAK);
paramaters.put(yourParamater);
}
yourObject.put("parameters", paramaters);
yourObject.put("Age", 25);
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
import org.json.JSONObject;
//other imports
//...
try {
//Create the JSON Object
JSONObject myObject = new JSONObject();
String parameters[] = new String[]{"JAK","1999"};
//use the method put to "fill" the values
myObject.put("name", "Katy");
myObject.put("parameter",(Object)parameters);
myObject.put("age", 25);
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","Katy");
jsonObject.put("parameters",new String[]{"JAK","1999"});
jsonObject.put("Age","25");
}catch (Throwable e){
e.printStackTrace();
}

Android - getString method error

I've got a slight problem with a getString function in my Android code.
I create a string and I want to use it to retrieve a String which is part of a JSON Array but I get the following error:
The method getString(String) is undefined for the type String
This is the specific code for this section:
private void read_JSON()
{
JSONArray jsa2 = new JSONArray();
for (int i=0; i < jsa2.length(); i++)
{
try
{
JSONObject jso2 = new JSONObject();
jso2 = jsa2.getJSONObject(i);
String one = one.getString("Blur");
//esbrinar com arreglar aixo!!
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
"Blur" is a String which is part of a JSONArray, defined here:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could you help me understand what I'm doing wrong?
Thank you very much.
Yours sincerely,
Mauro.
jso2.getString("Blur") might be what you're trying to call. I believe you want to extract a string from the JSONObject you just got from JSONArray. What you actually wrote is to extract string from the string you just defined.

JSONArray alternative in Android

I'm attempting to parse a string that contains an array of JSON objects, but the org.json.JSONArray is not supported until the API 19 (Kit-Kat) operating system. For obvious reasons I need to figure out a way around this. Is there a better alternative to this? Or am I using this method incorrectly?
Here is the code that keeps telling me I need API 19 or higher:
protected void onPostExecute(JSONArray result) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
info = new JSONArray(result);
for(int i = 0; i < info.length(); i++){
JSONObject c = info.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
String article = c.getString(TAG_ARTICLE);
String timestamp = c.getString(TAG_TIMESTAMP);
String datestring = c.getString(TAG_DATESTRING);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ARTICLE, article);
map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_DATESTRING, datestring);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE,TAG_ARTICLE, TAG_TIMESTAMP,TAG_DATESTRING }, new int[] {
R.id.title,R.id.article, R.id.timestamp,R.id.date_string});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
btw I am using an AsyncTask to put the information into a ListView. I have another class to fetch the result of the webpage. Thanks!
The new API 19 function you are using is:
info = new JSONArray(result);
Since result is already an JSONArray, why do you need to create another?
Dude try this framework is much better
https://code.google.com/p/google-gson/
or
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a solution under 19API lvl:
First of all. Make a Gson obj. --> Gson gson = new Gson();
Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)
The last step to get JsonArray...
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

Create an array of JSON Objects

I need to create a JSON Object for an Arraylist. Below is the code
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
serUri = "lists.json";
method = "post";
JSONObject jsonObject = new JSONObject();
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
try {
for (int i = 0; i < orderList.size(); i++) {
json.put("orderno", orderList.get(i).getOrderNumber()
.toString());
json.put("tableno", orderList.get(i).getTableNumber()
.toString());
json.put("itemname", orderList.get(i).getItemName().toString());
json.put("amount", orderList.get(i).getAmount().toString());
json.put("ordstatus", orderList.get(i).getOrderStatus()
.toString());
array.put(json);
}
catch (JSONException je) {
return false;
}
try {
jsonObject.put("list", array);
} catch (JSONException je) {
return false;
}
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}
The problem is its creating object with details of last row item at each position. Say if my orderList has 3 rows, the jsonObject created has 3 rows but with 3rd row data in all 3. Seems like its overriding data for all the rows with latest row fetched. I tried with couple of other ways but still not getting desired result. Please advise. Thanks.
JSON Object created:
{"list":[{"amount":"10.50","orderno":"0220130826163623","quantity":"1","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"},{"amount":"10.50","orderno":"0220130826163623","itemname":"Pollo Al Horno","tableno":"02","ordstatus":"placed"}]}
The above object has only last item in each row.
Your JSONObject json = new JSONObject(); should be within the loop.
Additionally, you should not do a get(i) each time to access properties (for performance). You can use the other construct of the for loop:
for (OrderDetailsData data : orderList) {
JSONObject json = new JSONObject();
json.put("orderno", data.getOrderNumber().toString());
// ...
}
Finally, maybe you should consider having a function that reads/writes a JSON object from an OrderDetailsData so that you can reuse the code in other webservices.
Small mistake
try {
for (int i = 0; i < orderList.size(); i++) {
JSONObject json = new JSONObject(); // update here
json.put("orderno", orderList.get(i).getOrderNumber()
.toString());
json.put("tableno", orderList.get(i).getTableNumber()
.toString());
json.put("itemname", orderList.get(i).getItemName().toString());
json.put("amount", orderList.get(i).getAmount().toString());
json.put("ordstatus", orderList.get(i).getOrderStatus()
.toString());
array.put(json);
}
catch (JSONException je) {
return false;
}
Look at this I'm trying to use GSON lib, try out this, I'm not tested. This should work fine.
From Json string to Json object this way:
String jsonStr = "{\"a\": \"A\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
For your code this should work fine:
public boolean submitOrder(ArrayList<OrderDetailsData> orderList)
{
serUri = "lists.json";
method = "post";
Gson gson = new Gson();
String jsonstr = new Gson().toJson(orderList);
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObject = element.getAsJsonObject();
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}
This following snippet will create array of json objects in single statement, it even performs null checks while creating json from object using Google's Gson library.
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
JsonElement ordersObj = gson.toJsonTree(orderList);
myObj.add("list", ordersObj);
}
You need to instantiate the json object inside the for loop.

Categories

Resources