I would like to create a generic class which create my jsonObject.
Is it possible to create a class which can create differents kind of objects like
{"chunkSize":10,"filters"
[{"field":"segmentOwners.id","operator":"EQUAL","value":"11578","valueType":"java.lang.Integer"},
{"field":"language","operator":"EQUAL","value":"FR","valueType":"java.lang.String"},
{"field":"customerId","operator":"EQUAL","value":"77","valueType":"java.lang.Integer"}]
,"orderBy":[{"field":"creationTime","order":"DESC"}],"page":0}
OR just a simple request:
{login:"mylogin",pwd:"mypwd"}
I tried something like:
#Override
protected JSONObject doInBackground(String... params) {
byte[] result = null;
Iterator iter = mData.entrySet().iterator();
JSONObject jsonObj = new JSONObject();
Iterator it = mData.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
try {
jsonObj.put((String) pairs.getKey(), (String) pairs.getValue());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
it.remove(); // avoids a ConcurrentModificationException
}
But i'm not sure that is the same kind of hashmap (string, jsonObjet...?)
If you want to create instances of JSONObject from JSON strings, just do the following:
JSONObject jsonObj = new JSONObject("<your json string>");
I'd create generic container class (i.e. DataContainer) which would expose unified API no matter of what data it holds (i.e. setFromJson(), getData()). Then create separate object for each data structure (i.e. DataLogin, DataSomething). Then when you fetch your json data from remote source, you could i.e. create DataLogin object and hand it to your DataContainer (or pass json to DataContainer so it could detect DataLogin should be used and create it itself, but that require some logic which may not be best approach). Then all methods that are expected to work on your json data can be handed DataContainer object and method could do getType() on it (you need to set type yourself of course), which would return what data is stored and then getData() to get the data iself to work on.
Related
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.
I am developing an Android Application which Fetch data from PHP Json.
I fetch the data of json successfully From JSON but my problem is when JSON is Empty it stops the application.
So I need to Know is How to know if the JSON is NULL or Return Nothing in ANDROID.
My empty JSON is:
[[]]
How to check that with Coding.
Please send me your suggestions.
My Full Code is On This Link:
Thanks Alot
JSONObject myJsonObject =
new JSONObject("{\"null_object_1\":[],\"null_object_2\":[null]}");
if (myJsonObject.getJSONArray("null_object_1").length() == 0) {
...
}
firstly you get key set of json.
Iterator<Object> keys = json.keys();
then check if any key exist then your json contain some value.
if(keys.hasNext()){ // json has some value
}
else
{
// json is empty.
}
after getting json from url first check for null by simply execute the code:-
if(yourjsonobject!=null){
//write your code here
}else{e
enter code here
//json is null
}
try like this,
if (<Your JSONobj>!= null ){
// do your parsing
}else{
}
1) json string "[[]]" means not empty jsonAarray it means your Outer JsonArray contains one element as JsonArray and your inner JsonArray is empty.
2) The reason your application is crashing/stopping is that JsonObject and JsonArray are incomptible types. You can not cast JsonArray to JsonObject. See
JsonArray and
JsonObject
3) You can always check the length of your JsonArray by
JsonArray#length() method.
also check
JsonArray#isNull if want to check wheter a JsonObject is NULL.
try {
JSONArray object = new JSONArray("[[]]");
if (object.length() > 0) {
JSONArray inner = object.getJSONArray(0);
if (inner.length() > 0) {
// do something
}
}
} catch (JSONException e) {
e.printStackTrace();
}
How I can convert any object (eg array) in json and get in the format string?
For example:
public String jsonEncode(Object obj) {
return jsonString;
}
You can use GSON library to convert any serializable objects into json String.
Here is the Tutorial how-do-convert-java-object-to-from-json-format-gson-api/
If you're asking how to do generic object serialization into json format in java, use reflection. Luckily, lots of the work is done for you, for example this or this.
If you want to go the other way, or specificially you want more control over your serialization, you can still use reflection with annotations. See the jackson mapper
For example:
Hashtable<String, String> capitales = new Hashtable<String, String>();
capitales.put("España", "Madrid");
capitales.put("Francia", "Paris");
String miStringArray[] = { "String1", "String2" };
And I do:
SONObject obj = new JSONObject();
try {
obj.put("name", "Jack Hack");
obj.put("score", miStringArray);
obj.put("otracosa", capitales );
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(obj);
Show:
{"score":"[Ljava.lang.String;#413587d0","otracosa":"{Portugal=Lisboa, Francia=Paris, Argentina=Buenos Aires, España=Madrid}","name":"Jack Hack"}
I have an app which sends a REST request to a server and receives a JSON response back. However, my REST client service on the app may send out several different types of REST request which will result in different responses causing different types of objects being created on the client android app. Each response will always be an array of some type of object.
Here is what I have so far:
#Override
protected List<?> doInBackground(String... urls) {
requestType = urls[0];
InputStream source = retrieveStream(Constants.REST_SERVER_URL + requestType);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
List<?> result = gson.fromJson(reader, List.class);
return result;
}
protected void onPostExecute(List<?> result) {
if(requestType.equals(Constants.GET_OSM_POI_NODES)) {
Log.v(TAG, String.valueOf(result.size()));
ArrayList<Node> nodes = new ArrayList<Node>();
for(Object o : result) {
// create a node object from the result
}
}
}
In the onPostExecute method I want to create the correct object based on what REST url was used. So for example, if the url corresponding to GET_OSM_POI_NODES was used then it would construct an ArrayList of node objects which consists of a latitude and a longitude along with an id. Here is a sample JSON response for such an object:
[
{
"id": 353941,
"lat": 754030751,
"lon": -39701762
},
...
The problem is that the result passed into onPostExecute is always a List of generic objects because I want it to be generic. I am not sure how to create Node objects from these generic types. Even if I don't use generics the objects passed into onPostExecute are list of StringMap and I don't know how to create different types of object from these.
Any ideas?
Anyone have any idea?
Thanks