Parse a JSON package in Android - java
I'm having some difficulties parsing a JSON package in Android.
I currently have everything set up so the JSON is an array of objects, then each object has an array of attributes. For example, say I have an object called Colors in my package. Then each Color entry would be in the Colors object. Each Color entry would also have entries for R, G, B values.
This type, I can deal with fine. However, I'm now running into an instance where one of those entries (where the R,G,B values would be) has an array within it. I'm not sure how to go about accessing that and processing it.
I'm going to update with an example of the JSON package, since I'm worried I wasn't very clear.
Edit: Here's the JSON. Say I want to access the R value in the ColorOverlays.
{"Package":[
{"Things":[{"ProgramId":73,"TypeId":68,"CategoryId":null,"CategoryName":null,"ThingId":121,"ThingName":"Mahalo","ThingDescription":"Get your festival on and snap some shots!","ThingPrice":0.00,"SellerProductId":null,"Number2":1342655700,"Number1":1342655700,"IsAvailable":true,"ImageOverlays":[{"ThingId":121,"ThingOverlayId":295,"ImageOverlayBase64":null,"ImageOverlayFileTypeExtension":null,"Width":1024,"Height":1024,"A":1.00000,"BlendModeId":1,"OrderNum":2,"IsUseSource":false}],"ColorOverlays":[{"ThingId":121,"ThingOverlayId":294,"R":157.00000,"G":71.00000,"B":187.00000,"A":0.52873,"BlendModeId":6,"OrderNum":1}],"ThingsampleImageBase64":null,"ThingsampleImageFileTypeExtension":"","ThingsampleImageWidth":546,"ThingsampleImageHeight":546,"Captures":[{"ThingCaptureId":87,"ThingId":121,"CaptureFrameOverlayId":null,"IsRemoved":false,"AddDate":1342637814,"LastUpdated":1342637814,"Saturation":0.0,"Contrast":0.0,"Brightness":0.0,"Low":null,"Mid":null,"High":null,"IsBlackWhite":null,"IsInvert":null,"IsSepia":null}],"IsRemoved":false},{"ProgramId":73,"TypeId":68,"CategoryId":null,"CategoryName":null,"ThingId":122,"ThingName":"Lots of Love","ThingDescription":"Use this one!","ThingPrice":0.00,"SellerProductId":null,"Number2":1342667100,"Number1":1342667100,"IsAvailable":true,"ImageOverlays":[{"ThingId":122,"ThingOverlayId":298,"ImageOverlayBase64":null,"ImageOverlayFileTypeExtension":null,"Width":1024,"Height":1024,"A":1.00000,"BlendModeId":4,"OrderNum":3,"IsUseSource":false}],"ColorOverlays":[{"ThingId":122,"ThingOverlayId":296,"R":213.00000,"G":86.00000,"B":143.00000,"A":0.77777,"BlendModeId":4,"OrderNum":1},{"ThingId":122,"ThingOverlayId":297,"R":127.00000,"G":127.00000,"B":127.00000,"A":0.50000,"BlendModeId":1,"OrderNum":2}],"ThingsampleImageBase64":null,"ThingsampleImageFileTypeExtension":"","ThingsampleImageWidth":546,"ThingsampleImageHeight":546,"Captures":[{"ThingCaptureId":88,"ThingId":122,"CaptureFrameOverlayId":null,"IsRemoved":false,"AddDate":1342649164,"LastUpdated":1342649164,"Saturation":0.0,"Contrast":0.0,"Brightness":0.0,"Low":null,"Mid":null,"High":null,"IsBlackWhite":null,"IsInvert":null,"IsSepia":null}],"IsRemoved":false}]}
]}
If this is not something that you would throw away after the first use, then you might consider taking this up a level by modeling Java objects after your domain.
Use any online JSON visualizer to see your JSON in 3D.
Then, follow the following tutorial.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
A sample of your code would be most helpful to try to help. Depending on how your RGB value array is built and passed. If it's a simple comma delimited string, then you could do:
try {
JSONArray jArray = new JSONArray(jString);
for (int i=0; i<jArray.length(); i++) {
JSONObject jo = jArray.getJSONObject(i);
String RGBVal = jo.getString("rgb_list");
String[] rgbArray = RGBVal.split(",");
....
Again, depends on how the entry is passed in JSON string.
Nevermind...
Related
How to copy all the values from one JSONObject to another?
I understand that it's perfectly possible to copy each individual component over one by one, but it's extremely messy to do and rather ugly. Isn't there a simpler way to copy all the values from one JSONObject to another? Important to note, I am using json-lib. I'm not opposed to switching tools if it's absolutely necessary. Point is, this is a rather inefficient way of doing things.
After hours of searching, I finally found the answer. I'm sort of embarrased that it's this simple. ~ Json-lib has a beautiful feature that allows you to take your current JSONObject and parse the entirety of the JSONObject into a String. And there already exists a method to build a JSONObject from a String. Therefore, all you need to do is turn the JSONObject into a String, and then back into a JSONObject. You could store the string as a variable (or use it as a return value), then simply take your preexisting JSONObject reference and use the method to rebuild the JSONObject from the String. Simple as that. EDIT - thought I would give a quick code example JSONObject a = /* pretend a has 100 elements inside */ String temp = a.toString(); JSONObject b = JSONObject.fromObject(temp); String temp2= b.toString(); if(temp.equals(temp2)){System.out.println("Well done.");}
Converting JSON Object(s) from file using Java
I have a JSON file with no clue on how data will be in it nor the structure of data. The only thing known is that it will have either an array of JSON objects or a single JSON object. I need to get each object from the file and store it as a separate item. In case of array of objects in the file, I should get an array of JSON strings which I can store in DB. Basically, I need to read this file and separate out each JSON object from it and store it in DB as a string. One of the ways to do it was to use JACKSON ObjectMapper and assign these items to a Hashmap as key value pairs, but I am not sure though how it can be done If there are list of JSON Objects in the file. Sample JSON File: [ { "name":"Bob", "type":"Email", "from":"a#a.com", "to":"b#B.com", "attachments":[...], . . . } ]
Do you know the Object structure that the JSON has(let it be Array or a single one) ? If Yes, First load the json string form the file into an in memory string. check the string for Array existence, by searching for '[',']' in the outer structure of multiple occurrences of '{' or '}' once you know whether you have an array or a single object, you can pass it as object reference to either Jackson or GSON parsers create in memory Array of JsonObject.class say List. It is actually better to enclose this List inside another class. say myJsonObjects and have a List inside it. Let us see GSON parsers (by google), though Jackson can also be used in the similar implementation Gson gson = new Gson(); if(isArray){ myJsonObjects jsonArray = gson.fromJson(jsonStringFromFile,myJsonObjects ); } else{ gson.fromJson(jsonStringFromFile,JsonObject); } http://google-gson.googlecode.com/svn-history/trunk/gson/docs/javadocs/com/google/gson/Gson.html
Jackson is my favorite JSON-to-POJO library. It doesn't really matter where you're loading the JSON from (a URL or from the filesystem), there are handlers for several input sources. Here's an example: Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class); As far as having an unknown number of JSON structures that you're about to parse, the first thing that comes to mind is to have a mapper for each type you're expecting. You could then wrap the parsing code in try/catch blocks so that if the first fails with whatever exception Jackson gives you when encountering an unexpected format, you can then try the next format and so on. If you're just trying to generically parse JSON that you don't know the structure of beforehand, you can try something like this: mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {}); The documentation for Jackson is pretty good-- giving it a solid read-through should definitely help. Here's a good five minute tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
I prefer use Gson: Gson gson; Map<String, Object>parameters=gson.fromJson(myString); the rest is iterate the map, i hope help you
Java: Getting object associated with enum
I have an ArrayList full of custom objects. I need to save this ArrayList to a Bundle and then retrieve it later. Having failed with both Serializable and Parcelable, I'm now simply trying to somehow save the objects that are associated with the indexes in the ArrayList, then checking these when restoring the Bundle and adding the objects back in. What I have is something like this: When saving the Bundle: //Create temporary array of the same length as my ArrayList String [] tempStringArray = new String[myList.size()]; //Convert the enum to a string and save it in the temporary array for (int i = 0; i<myList.size();i++){ tempStringArray [i] = myList.get(i).getType(); //returns the enum in string form } //Write this to the Bundle bundle.putStringArray("List", tempStringArray); So I now have an array of strings representing the enum types of the objects that were originally in the ArrayList. So, when restoring the Bundle, what I'm trying is something like this: //Temporary string array String[] tempStringArray = savedState.getStringArray("List"); //Temporary enum array ObjectType[] tempEnumArray = new ObjectType[tempStringArray.length]; for (int i = 0; i<tempStringArray.length;i++){ tempEnumArray[i]=ObjectType.valueOf(tempEnemies[i]); } So, now I have the enum type of each item that was originally in the ArrayList. What I'm now trying to do now, is something like (would go inside the for loop above): myList.add(tempEnumArray[i].ObjectTypeThisEnumRefersTo()); Obviously the "ObjectTypeThisEnumRefersTo()" method above doesn't exist but this is ultimately, what I'm trying to find out. Is this possible or perhaps there is some other way of doing this?
To get an enum value of the enum type Enemy from a string, use Enemy.valueOf(String). Enemy.valueOf("SPIDER") would return Enemy.SPIDER, provided your enum looks like enum Enemy { SPIDER, BEE}; EDIT: It turns out Zippy also had a fixed set of Enemy objects, each mapped to each value of EnemyType, and needed a way to find an Enemy from a given EnemyType. My suggestion is to create a HashMap<EnemyType, Enemy> and put all the objects in there upon creation, then at deserialization convert strings to enum values and enum values to Enemy objects using the hashmap. It later occurred to me though that depending on how much logic you have in Enemy, you might want to consider scrapping either Enemy or EnemyType and combine them into one parameterized enum, similar to the example with Planet over here:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html That would spare you from having to go two steps from a string to your final object and simplify things a bit as you wouldn't need any hashmap after all.
Java multiple type data structure
Is there a data structure in Java which can store different types in it? I mean like storing in an array different types (which actually does not work).
try List<Object> list = new ArrayList<Object>(); more info in http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
You could use an object array but that creates problems when the time comes to retrieve the objects you have stored. However, if you want to get data out of the array, you can only get it as an Object. The following won't work: int i1 = objects[1]; // Won't work. Integer i2 = objects[2]; // Also won't work. You have to get it back as an Object: Object o = objects[0]; // Will work. You can't get back the original form now.
JSONObject.append - result is nested array?
I have seen this question and understand the answer, but can not use it in my scenario. My scenario: I retrieve data via JPA from a mysql database and want to put this data into a JSONObject like this { "A":["1","2","3"], "B":["1","2","3","4"], "C":["1","2"] } The problem is I do not know how many arrays I will retrieve. It could be 1 or it could be 200, depending on the data in the database. If I append the data into a JSONObject like this: import org.apache.tapestry5.json.JSONObject // ... JSONObject data = new JSONObject(); for (Value val : values) data.append(val.getName(), val.getValue()); I'll get {"val_name": [[["1"],"2"],"3"], ...} Is there a way to use JSONOBject.append without creating JSONArrays and puting them into the JSONObject, which will result in a nested JSONObject?
A JSON object is a "dictionary" -- a map between name and value. A JSON array is a sequential list of values, with only the ordinal position of the value identifying it. It makes no sense to "append" to the object -- you add new name/value pairs to it (although they apparently call it appending, just to confuse you). If, within an object, you want something like "A":["1","2","3"] then you necessarily must insert an array (as the value of a name/value pair) into the object. But note that either before inserting the array into the object or after you can append additional values to the array. You just need to get/save a reference to the array. In your above example you're making the mistake of appending to the object rather than the array.