create jsonArray with GsonBuilder or Gson - android

I want to send my ArrayList<Orto> listOrtowith json to my server. Here is my code
String url = serverUrl + "addOrto1212"; //tırnak içi addOrto olacak
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
try{
JSONObject json = new JSONObject();
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(listOrto).getAsJsonArray();
json.put("list",myCustomArray);
Log.d("******************json",json.toString());
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
client.execute(post);
}catch(Exception e){
//
}
Let see Logcat;
03-30 09:24:18.655 21698-22331/com.emato.microorthodontist D/******************json: {"macid":"C9:3F:C1:B1:6F:1F","list":"[{\"date\":\"2016\/03\/30\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":31,\"dest\":0,\"melvalue\":11},{\"date\":\"2016\/03\/29\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":16,\"dest\":0,\"melvalue\":95},{\"date\":\"2016\/03\/28\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":17,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/27\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":18,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/26\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":19,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/25\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":20,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/24\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":21,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/23\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":22,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/22\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":23,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/21\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":24,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/20\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":25,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/19\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":26,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/18\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":27,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/17\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":28,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/16\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":29,\"dest\":0,\"melvalue\":0},{\"date\":\"2016\/03\/15\",\"mac\":\"C9:3F:C1:B1:6F:1F\",\"id\":30,\"dest\":0,\"melvalue\":0}]"}
"list" is return me one String by my listorto but I want jsonArray. Where is my mistake please help..

you can create POJO classes to represent the data you are working with, ex:
public class MyData {
private String macid;
private ArrayList<MyListItem> myList= new ArrayList<MyListItem>();
// create setters and getters
}
public class MyListItem {
private String date;
private String mac;
private Integer id;
private Integer dest;
private Integer melvalue;
// create setters and getters
}
then use GSON to convert to and from JSON:
populate data objects...
MyData mydata = new MyData();
mydata.setMacid("some:mac:id");
MyListItem item = new MyListItem();
//item .set ... set other values for the item
mydata.getMyList().add(item);//add as many items as you want
Create an instance of Gson:
Gson gson = new Gson();
1- To Json:
//from object to json string
String mydataAsJson = gson.toJson(mydata, MyData.class);
2- From Json:
//from json string to object
String jsonStr = getJsonFromServer();
MyData mydata2 = gson.fromJson(jsonStr, MyData.class);

Related

Array as parameter in retrofit

I have an issue with my parameters passing in retrofit, My problem is need to send int array ([3,1,2]) as one of the parameters in a POST method with retrofit 2, other parameters are as string. (ex: tips - "10", amount-"100", service-ids -[3,1,2]). How can send parameters like above in example.
You can use ArrayList such as:
#FormUrlEncoded
#POST("service_name")
void functionName(
#Field("yourarray[]") ArrayList<String> learning_objective_uuids, #Field("user_uuids[]") ArrayList<String> user_uuids, #Field("note") String note,
Callback<CallBackClass> callback
);
You can follow this link.
Or you could use JSONObject like so:
#POST("demo/rest/V1/customer")
Call<RegisterEntity> customerRegis(#Body JsonObject registrationData);
registrationData:
private static JsonObject generateRegistrationRequest() {
JSONObject jsonObject = new JSONObject();
try {
JSONObject subJsonObject = new JSONObject();
subJsonObject.put("email", "abc#xyz.com");
subJsonObject.put("firstname", "abc");
subJsonObject.put("lastname", "xyz");
jsonObject.put("customer", subJsonObject);
jsonObject.put("password", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
JsonObject gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString());
return gsonObject;
}
You can define an object reflecting the structure of the POST body:
#POST("/pathtopostendpoint")
Call<ResponseObject> postFunction(#Body final RequestBody body);
with your RequestBody being defined as following (if you use the GSON converter, tweak the naming of the field with #SerializedName):
class RequestBody {
String tips;
String amount;
int[] serviceIds;
RequestBody(final String tips, final amount String, final int[] serviceIds) {
this.tips = tips;
this.amount = amount;
this.serviceIds = serviceIds;
}
}
and build the request call like that:
final Call<ResponseObject> call = retrofitService.postFunction(
new RequestBody("10", "100", new int[]{ 3, 1, 2 })
);

How to parse JSONArray with variable key (GSON)?

My json is :
{"array":[{"US":"id_123"},{"UK":"id_112"},{"EN":"id_1112"}...]}
My classes are:
class LocaleResponce implements Serializable{
#SerializedName("array")
List<Locale> array;
}
class Locale implements Serializable{
#SerializedName("title")
String title;
#SerializedName("id")
String id;
}
I'm tried to make this:
Gson gson = new Gson();
Type type = new TypeToken<LocaleResponce >(){}.getType();
LocaleResponce response = gson.fromJson(cacheJsonObject.toString(), type);
it doesn't work or is it an issue of server?
It can be achieved by creating custom JsonDeserializer.
Your deserializer class will look something like
public class CityListDeserializer implements JsonDeserializer<List<City>>{
#Override
public List<City> deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<City> cityList = new ArrayList<>();
JsonObject parentJsonObject = element.getAsJsonObject();
Map.Entry<String, JsonElement> entry = parentJsonObject.entrySet().iterator().next();
Iterator<JsonElement> iterator = entry.getValue().getAsJsonArray().iterator();
City city;
while (iterator.hasNext()){
JsonObject cityJsonObject = iterator.next().getAsJsonObject();
for(Map.Entry<String, JsonElement> entry1 : cityJsonObject.entrySet()){
city = new City();
city.cityName = entry1.getKey();
city.id = entry1.getValue().toString();
cityList.add(city);
}
}
return cityList;
}
}
You can use it with
try {
JSONObject object = new JSONObject("{\"array\":[{\"US\":\"id_123\"},{\"UK\":\"id_112\"},{\"EN\":\"id_1112\"}]}");
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(new TypeToken<ArrayList<City>>() {}.getType(), new CityListDeserializer());
Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
List<City> cityList = gson.fromJson(String.valueOf(object), new TypeToken<ArrayList<City>>() {}.getType());
} catch (JSONException e) {
e.printStackTrace();
}
Your City class will be
public class City {
String cityName;
String id;
}
You can generate classes for Json using websites like http://www.jsonschema2pojo.org/ etc in your case the array array variable, does not have an array of homogeneous objects {"US":"id_123"},{"UK":"id_112"},{"EN":"id_1112"} these are all objects of different DataTypes because, the parameter keys are different, so for parsing this you cannot use a Pojo. The parameters vary from UK US EN etc, the solution here is either to ask the person who is developing the api to send Json that is Consistent, the array that you have received is not type safe, if you want to use this in Java you have to write lots of lines of code. For example you can get the value of the parameter "UK" like this
cacheJsonObject.get("array").getAsJsonArray().get(1).get("UK").getAsString();
This would return the value id_112 for instance.

Deserializing an object that contains a single list with gson

I have the following json I want to deserialize:
{
"locations": [{
"id": 17,
"account_id": 11,
"name": "The Haunted Lexington",
"radius": 100
}]
}
(In this particular instance, there's only one Location, but there can be many).
I deserialize this using Gson with the following code:
Gson gson = new GsonBuilder().create();
LocationList ll = gson.fromJson(jsonString, LocationList.class);
I have the following classes defined:
public class Location {
#SerializedName("id")
private long mId;
#SerializedName("account_id")
private long mAccountId;
#SerializedName("name")
private String mName;
#SerializedName("radius")
private int mRadius;
public long getId() {
return mId;
}
public String getName() {
return mName;
}
}
and:
public class LocationList {
#SerializedName("locations")
private List<Location> mLocations;
}
The thing is, I have a bunch of these "dummy" classes that contain a single object that's a list of other objects (e.g. UserList, MessageList, etc...)
What I'd like to do is have the above json parsed somehow so I can skip defining the intermediate class definition of LocationList, like so:
Gson gson = new GsonBuilder().create();
// Use the same json as above, but skip defining the superfluous "LocationList" class
List<Location> ll = gson.fromJson(jsonString, "locations", ArrayList<Location>.class);
Is there a way I can do this, perhaps by providing a custom deserializer?
I faced a similar problem not long ago, and solved it like this
// Parse the JSON response.
JSONArray jsonArray = new JSONArray(response);
List<Location> locations = new ArrayList<Location>();
/*
* Create a Location object for every JSONObject in the response,
* and add it to the list.
*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Location location = new Gson().fromJson(jsonObject.toString(),
Location.class);
locations.add(location);
The approach here is to loop over every Location in the locations array in the JSON, extracting them one by one and then adding them to a list.
The JSON I worked with had a list as root object, so you probably can't use this JSONArray jsonArray = new JSONArray(response);. Something like this might better suit your situation
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray locationsJsonArray = jsonObject.get("locations");
I have not tested these last 2 lines, but I think you get the idea.
I hope you can use this to solve your problem.
I'm currently using a simple method to achive your goal:
private static <T> List<T> getList(final String jsonVal, final String listTag, T t) {
try {
JsonObject jsonObject = (JsonObject)(new JsonParser()).parse(jsonVal); // root JsonObject. i.e. "locations"
JsonArray jsonArray = (JsonArray)jsonObject.get(listTag);
Gson gson = new GsonBuilder().create();
List<T> list = gson.fromJson(jsonArray, new TypeToken<List<T>>() {}.getType());
return list;
} catch (Exception e) {
throw new IllegalArgumentException("Unexpected json structure!", e);
}
}
Example usage:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
String jsonString = "{\"locations\":[{\"id\":17,\"account_id\":11,\"name\":\"The Haunted Lexington\",\"radius\":100}]}";
List<Location> list = getList(jsonString, "locations", new Location());
This method should be used for your orther classes, such as:
List<User> userList = getList(jsonString, "users", new User());
List<Message> messageList = getList(jsonString, "messages", new Message());

How to create Json object

I have database like which have three coloums( id(integer) , startdate(text), enddate(text),).
I want to read all the entries for these coloums, convert them to Json and send to web url.
I know how read values but did not know how to make Json from these values.
Please any coding help...
Why don't you try:`
JSONObject object = new JSONObject();
try {
object.put("id", id);
object.put("startDate", startDate);
object.put("endDate", endDate);
} catch (JSONException e) {
e.printStackTrace();
}`
Then send the json object via a http post
`
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}`
so if for example you want to create a JSON object containing all the triplets you get from an SQLite db it would be:
String query = "SELECT *"+
"from "+TABLE_NAME;
Cursor c = db.rawQuery(query,new String[]{});
Log.d("query",query);
c.moveToFirst();
while(c.moveToNext()){
try {
int id = c.getInt(c.getColumnIndex("ID"));
String startDate = c.getString(c.getColumnIndex("START_DATE"));
String endDate = c.getString(c.getColumnIndex("END_DATE"));
object.put("id", id);
object.put("startDate", startDate);
object.put("endDate", endDate); }}
where ID, START_DATE and END_DATE are the corresponding names of the fields in DB.
I cannot test my code right now but I believe it works
Here is how to make an JSON object:
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", idValue);
jsonObject.put("startDate", endDateValue);
jsonObject.put("endDate", endDateValue);
You can also get the JSON as String by doing:
jsonObject.toString();
JSONObject json = new JSONObject();
json.put("id", id);
json.put("startdate", startdate);
json.put("enddate", enddate);
Using the jackson library, you can convert a map or java bean to a json string or generate a map or javabean from a json string. you might write a util class:
public class JsonUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String convertToJsonStr(Object model) throws IOException {
return MAPPER.writeValueAsString(model);
}
#SuppressWarnings("unchecked")
public static Map<String, Object> readFromStr(String content) throws IOException {
return readFromStr(content, Map.class);
}
public static <T> T readFromStr(String content, Class<T> clazz) throws IOException {
return MAPPER.readValue(content, clazz);
}
}

How to download a JSON Object array from URL, and Store for Android App?

I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...

Categories

Resources