How can I send a array list from a servlet to an Android application?
To the point, you need to convert it to a String in some standard format which can then be parsed and built using the existing libraries. For example, JSON, XML or CSV, all which are standardized and exchangeable string formats for which a lot of parsing/building libraries exist in a lot of programming languages.
Android has a builtin JSON parser in the org.json package. It has even a builtin XML parser in the org.xml.sax package. I'm not sure if there's a builtin CSV library, but there appears to be none. Java EE has in flavor of JAXB a great builtin XML parser, but it doesn't have a builtin JSON parser. Only the JAX-RS implementations (Jersey, RESTeasy, etc) provide a JSON parser. If you can change your servlet to be a JAX-RS webservice instead, you'll have the benefit of being able to return both XML and JSON with very minimal effort. See also Servlet vs RESTful.
Which format to choose depends on the sole functional requirements. For example, is the servlet supposed to be reused for other services? What are the target clients? Etcetera.
In any way, the JSON format is usually more terse and lately more popular than XML, so I'll just give a kickoff example which transfers the data in the JSON format and I'll assume that you really want to do it with a plain vanilla servlet instead of JAX-RS. For this example, you only need to download and drop a JSON library such as Gson in /WEB-INF/lib in order to convert Java objects to JSON in the servlet.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
This will build and return the List in the following JSON format:
["item1","item2","item3"]
This is in turn parseable by org.json API in Android as follows:
String jsonString = getServletResponseAsStringSomehow(); // HttpClient?
JSONArray jsonArray = new JSONArray(jsonString);
List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
// Now you can use `list`.
If its a pull based model you can send the HTTP GET request to the servlet endpoint from your android app, and the HTTP Response could be a JSON object, created from an array list.
Related
I am trying to build an android app that uses the github api.
I am facing an issue with JSON parsing.
I have a function that looks for JSONArray and produces the corresponding JSON data to show them in the UI, but the problem is the function works only when the JSON root is an array.
For ex-
when the url is "https://api.github.com/users", it works perfect, since the root is an array but now when I go to url such as "https://api.github.com/users/mojombo", the JSON root becomes an object. How do I parse it now in order to show the data in the UI ??
Do I have to write separate function for JSONObjects??
**The java function is **
private void makeJSON(String res) throws JSONException {
JSONArray root = new JSONArray(res);
for (int i =0; i<root.length();i++){
JSONObject jsonObject= root.getJSONObject(i);
String name = jsonObject.getString("login");
int id = jsonObject.getInt("id");
}
}
The answer is yes. Here you try to parse different types of objects (users list and particular user info) in single function. This is violation of single responsibility principle.
You can divide this function in 2 (to parse users list and user data) but better is to use Retrofit 2 for this.
In my app I have to send a big dataset back to our server for processing. I am using ksoap for all my requests to pull stuff from the server with your normal xml properties and attributes but in the one call I have to use a dataset to send information.
Is there anything in the ksoap library for android that makes this whole process easier?
basically right now I am just constructing this huge string with all these header,tags and a shcema
example:
String header = "<mmAps diffgr:id=\"mmApps"+String.valueOf(count)+"\" msdata:rowOrder=\"0\" diffgr:hasChanges=\"inserted\">\n";
String ecmmaID = "<ECMMAID>"+c.getString(c.getColumnIndex(Apparatus.APP_ECMMAID))+"</ECMMAID>\n";
etc..
String datasetToSend = header+ecmmaID+....;
and then I would make the request passing in the big string
Please tell me there is some sot of easier way to do this.
Also changing away from data sets is not a possibility since its out of my control
JSON is the best option that you can use easily with KSOAP. This would be structured and far more better than your generated string.
1. Make identical Model class in android and your server (C#.Net, Java, etc.)
// In Android
class MyData {
String someThing;
public getSomeThing() {}
//...
}
2. Encode that dataset to JSONArray in android using model class
// Create JSON Objects in loop for entire dataset
JsonObject jo = new JsonObject();
jo.add(myData.getSomthing());
// Add all JSON Objects in JSONArray
JSONArray jArray = new JSONArray();
jArray.add(jo);
3. Send this JSON as string using KSOAP
String toSendViaKsoap = jArray.toString();
4. Decode that string from json to list of model class on server.
Depending on your server language, decode that string and create objects of similar class of step 1 in native language here, and do whatever you want.
If you have .NET server application, there are lots of free libraries to dacode json inclulding builting json support as well. but I will prefer this one.
Hope this helps..:)
I have an XML web service. I want to parse this XML and I want to store in an separate textviews. The following is an XML content, and I have finished getting it in a String variable.
{
"30_year_rate": 4.25,
"30_year_pi": 196.78,
"30_year_apr": 4.375,
"20_year_rate": 4.375,
"20_year_pi": 250.37,
"20_year_apr": 4.5,
"15_year_rate": 3.75,
"15_year_pi": 290.89,
"15_year_apr": 3.875,
"10_year_rate": 3.625,
"10_year_pi": 397.89,
"10_year_apr": 3.75,
"5_year_arm": 2.75,
"5_year_pi": 163.3,
"5_year_apr": 2.875,
"7_year_arm": 3,
"7_year_pi": 168.64,
"7_year_apr": 3.125,
"3_year_arm": 4,
"3_year_pi": 190.97,
"3_year_apr": 4.125,
"5_year_io_arm": "N/A",
"5_year_io_pi": "N/A",
"5_year_io_apr": "N/A",
"QuoteID": 1449,
"Licensed": "N"
}
How can I parse this data? I want to convert it to a JSON object and retrieve it, or any other reasonable approach.
If what you're getting back from the webservice is the string above, then you already have a JSON string. To create an object that can retrieve information from it, use something like JSONObject.
JSONObject object = new JSONObject(your_string_variable);
double thirtyYearRate = object.getDouble("30_year_rate");
String licensed = object.getString("Licensed");
etc.
You might (will) run into some issues where you try to pull a double from a JSON field that contains a string; i.e., the "N/A" fields above. You'll likely have to pull them out as strings and then try to parse doubles from them, and if the parsing throws an exception, you'll know it's a string.
Alternately, you could look into JSON binding with something like Jackson, which apparently runs on Android.
To parse JSON, you could use the built in JSONObject org.json Or Json-lib if you use an old version of android.
To parse XML, use XMLPullParser. A sample can be found here: Parsing XML Data
I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.
I have this Json model and I want to parse only one object:
{"CodeMsg": "Server Local Time", "server_time": "2012-03-19 19:59:30", "CodeResult": "OK"}
How can I do that?
There are a number of libraries available to parse JSON. Two that are commonly used are:
Gson - http://code.google.com/p/google-gson/
Jackson - http://jackson.codehaus.org/
With both you do this:
Create a plain java object to represent your data - e.g. a class CodeMsg
Use the library to provide the JSON string/stream, and the type (CodeMsg) and an object of that type is created, with its members set according to the JSON (e.g. server_time, CodeResult, etc)
They are very easy to use.
var data = {"CodeMsg": "Server Local Time", "server_time": "2012-03-19 19:59:30", "CodeResult": "OK"};
JSONObject obj1 = new JSONObject(data);
and then use obj1.getJSONString('CodeMsg');