JSON parsing to Java - Android application - java

I need help with parsing json string in Java Android Appl.
Text of JSON file:
{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}
How can get values: location_id, name, latitude, longitude.
Thanks, Michal.

Using manual parsing you can implement it like this:
JSONArray pages = new JSONArray(jsonString);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("page");
String address = jsonPage.getString("url");
String name = jsonPage.getString("name");
String status = jsonPage.getString("status");
}
in your case note that your outer elemnt data is type of JSONObject and then you have a JSONArray
mine json file:
[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]
note that mine starts from [, which means an array, but yours from { and then you have [ array inside. If you run it with a debugger, you can see exactly what´s inside your json objects.
There are also better approaches like:
Jackson
Jackson-JR (light-weight Jackson)
GSON
All of them can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

First of all, you need to know about Json parsing in android, so for that first read this: JSONObject, in that class, you will see the below methods:
getJSONArray(String name)
getJSONObject(String name)
getString(String name)
and many more methods to be used while implementing JSON parsing in android.
Update:
And if you are still confused then click on below link to have many examples available on web: Android JSON Parsing

You need to use the GSON lib
http://code.google.com/p/google-gson/
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

If you mean to navigate easily the Json Tree, you can use JSON Path, that is query system, similar to XPath to XML, that you can use to pick some elements in a json tree using text expressions.
http://code.google.com/p/json-path/ That's a good implementation
If you just mean that you want to parse that JSon you can use Gson from google (that is compatible with Android I guess).

This contains a complete example for your case.

Related

Java[Gson] - How to assign the correct type automatically to Json

I'm trying to build json using Gson dynamically as following ,
loop through existing fields and take the name and value and build json based on it,
so for an input:
a="AString"
B=true
C=null
D=[1,2,3]
E={"a":"b"}
will get valid json as:
{
"a":"AString",
"b": true,
"c": null,
"d":[1,2,3],
"e":{"a":"b"}
}
code:
JsonObject jsonObject = new JsonObject();
Field OutPortList[] = BBClass.class.getDeclaredFields();
for(Field x : OutPortList)
{
jsonObject.addProperty( x.getName() , x.get(this));
}
Getting error :
jsonObject.addProperty( String , String ) is not applicable
also tried casting :
jsonObject.addProperty( x.getName() , x.getType().cast(x.get(this)) );
Not sure but i guess it relate to type ,
as i try with x.get(this).toString() and its work but this will cast everything to string type.
I'm not sure what would be the correct way to handle the type automatically without casting it each time to the correct type.
You are trying to squeeze a java.lang.Object into a JsonElement (the add method) or a String (the addProperty method). The type of the field could be anything, including types that have no direct counterpart in json.
The easiest way would be to rely on the marshalling gson provides.
Gson gson = new Gson();
gson.toJson( this );
which yields a json formatted string.
If for some reason you still want to iterate the fields manually, you could still use gsons type marshalling for building the properties. Like this:
JsonObject jsonObject = new JsonObject();
Field[] OutPortList = Test.class.getDeclaredFields();
Gson gson = new Gson();
for(Field x : OutPortList)
{
jsonObject.add( x.getName(), gson.toJsonTree( x.get(this) ) );
}
Note, that you should consider sticking to Java naming conventions by using lowerCamelCase on variable names.

Iterate JSON and get fields from JSON

I've tried different solutions but I'm not able to iterate through this JSON and/or get direct specific values.
Could any one help on:
Iterating through all the fields sequentially.
Getting direct access to some fields (eg. when getting this response, access directly to "packet-count" where its value equals 3281).
{"flow-node-inventory:flow":[{"id":"42","priority":10,"table_id":0,"opendaylight-flow-statistics:flow-statistics":{"packet-count":3281,"byte-count":317738,"duration":{"nanosecond":252000000,"second":3432}},"idle-timeout":10000,"cookie":31,"instructions":{"instruction":[{"order":0,"apply-actions":{"action":[{"order":0,"output-action":{"output-node-connector":"1","max-length":0}}]}}]},"match":{"ethernet-match":{"ethernet-source":{"address":"00:00:00:00:00:02"},"ethernet-destination":{"address":"00:00:00:00:00:01"}}},"hard-timeout":50000,"flags":""}]}
I tried to use org.json but any other library would be okay.
You will have to check the structure of your JSON Object and create a structure for the entities you encounter accordingly. For instance, the first thing in your JSON object is an array, so this is the first thing you should care about. Imagine it as a continuous encapsulation. Check the code below for more information.
JSONObject jobj = new JSONObject(stringJson);
JSONArray flowNodeInv = jobj.getJSONArray("flow-node-inventory:flow");
for (int i = 0; i < flowNodeInv.length(); i++){
JSONObject segment = (JSONObject) flowNodeInv.get(i);
JSONObject stats = segment.getJSONObject("opendaylight-flow-statistics:flow-statistics");
int number = stats.getInt("packet-count");
System.out.println("packet-count: "+ number);}
Try This
jObject = new JSONObject(contents.trim());
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
}
}
To get direct access to the fields you can create a Java Object from the JSON String using an ObjectMappet (com.fasterxml.jackson). For example:
ObjectMapper mapper = new ObjectMapper();
MyClass myClass = mapper.readValue(jsonString, MyClass.class);

How to deal with json string in java servlet

A variable called wrongAnswers which is an array of javascript objects is generated on the client.
It has the form
wrongAnswers = [
{"wrongAnswer": "Manzana", "wrongQuestion": "apple"},
{"wrongAnswer": "arbol", "wrongQuestion": "tree"}
]
JSON.stringify(wrongAnswers) is used and the variable is then sent to a servlet using a form.
Once it is in the servlet, i want to convert the JSON into a Java Arraylist.
I have a class Answer with 2 variables, wrongAnswer and wrongQuestion. I would like to iterate through the JSON array, and for each object, create an Answer object with the value of wrongAnswer and wrongQuestion in that JSON Object. Each time, adding the Answer object to an ArrayList so in the end, i have an ArrayList of Answers corresponding to all the values from the JSON.
At the moment, I can use request.getParameter("json") which gets me a String with the JSON data. However, i am not sure what to do with this String.
Is there a way i can easily convert a String holding JSON data into a JsonArray or JsonObject, which i can easily iterate through, getting the value of the name: value pairs in each object?
Some example code would have been nice, but there is many ways to parse and work with JSON.
One way you could try is:
JSONArray json = new JSONArray(jsonString);
ArrayList<String> array = new ArrayList<String>();
for(int index = 0; index < json.length(); index++) {
JSONObject jsonObject = json.getJSONObject(index);
String str= jsonObject.getString("wrongAnswer");
array.add(str);
}
Try using jackson for parsing the json string: https://github.com/FasterXML/jackson
For an example, look up: How to parse a JSON string to an array using Jackson

how to convert a string[] to json

I declared an array as below
String[] finalcodes = new String[50] ;
and assigning some values to it finally when I print finalcodes it results as below.
["aaa","bbb","ccc"]
but my requirement is to get it as a json object
so please suggest me how to convert my string array to JSON Object.
You can use jackson library also check your json is valid;
http://jackson.codehaus.org/ / http://jsonformatter.curiousconcept.com/

Android, Parsing JSON object

When i call server its response is based of json object. Actually, I know how to parse JSON object but this response is strange for me. Server response is:
{"body":"Not Available!","clazz":"SoccerMatchPreview","id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978},"publishedDate":"2012-06-08 17:00:00 +0100","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595","title":"Poland vs Greece"}
Those Information that I need are body, publishedDate, refKey and title. The code that i have written based of JSON object is this:
JSONObject jObject = new JSONObject(response);
JSONArray contestantObjects = jObject.getJSONArray("id");
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
But because it doesn't have "[]" I think it's not JSON object. therefore, I wrote another code based JSON array.
JSONArray contestantObjects = new JSONArray(response);
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
but result is same and Logcat shows:
Value {"id":{"timeSecond":1337861978,"time":1337861978000,"new":false,"machine":415106952,"inc":-2024241794},"body":"Not Available!","title":"Poland vs Greece","publishedDate":"2012-06-08 17:00:00 +0100","clazz":"SoccerMatchPreview","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595"} of type org.json.JSONObject cannot be converted to JSONArray
any suggestion would be appreciated. Thanks
JSONArray contestantObjects = jObject.getJSONArray("id");
Your error is here, id is itself a complex object, not an array.
"id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978}
Therefore, after getting the id JSON object, you should be able to get the individual attributes, e.g. inc, machine, new, time, and timeSecond.
JSONObject idObject = ...getJSONObject("id");
String machine = idObject.get("machine");
A JSON array data structure would have looked like this: [] signifies an array.
For example, "Animals":["Pig", "Cat", "Dog"].
In another example, it can also be an Array of complex objects, "Animals":[{"name":"AAA", "blood":"A"}, {"name":"BBB", "blood":"B"}].
EDIT: Here is a good JSON visualizer i would recommend.
http://jsonviewer.stack.hu/

Categories