How do i convert from this org.json into jackson parser? - android

JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArray = jsonObj.getJSONObject("query").getJSONObject("results").getJSONArray("row");
int arrayCount = jsonArray.length();
for(int i=0; i < arrayCount; i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
String col0 = jsonData.getString("col0");
String col1 = jsonData.getString("col1");
// etc, etc ...
// put those values in arrays or whatever here.
}
What is the syntax for the same operation but using the 'Jackson' parsing libary?
I currently have:
JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createParser(res);
JsonToken current;
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("row")) {
if (current == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node = jp.readValueAsTree();
Log.e("KFF", node.get("col0").asText());
}
} else {
Log.e("KFF", "Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
Log.e("KFF", "Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Example of the data i need to parse:
http://pastebin.com/rhD2d9fx

Related

Parsing json response extraction

// Reading json file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"boysquestion.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
// Try to parse JSON
String question = null;
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("category");
// JSONArray has x JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
question = jsonObj.getString("question");
int no_score = jsonObj.getInt("no_score");
int yes_score = jsonObj.getInt("yes_score");
int category = jsonObj.getInt("category");
Log.d("question boys", question);
tvBoyGirl.setText(question);
Log.d("random", question);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Json Response ,how to extract all things :
[{"category":1,"no_score":3,"question":"Does he ever send the first text of a conversation?","yes_score":1},{"category":1,"no_score":3,"question":"Does he reply with two or three word answers?","yes_score":1}]
Above is json response.. i want to extract each and everything..i.e category,no_score,yes_score and question..
i have tried
question = jsonObj.getString("question");
but i am not getting.. can anyone help me to extract.
Json object start with { and json array starts with [. In your case the json is an array.
So read it as an array instead of jsonobject.
i.e, you need to read it like below.
JSONArray jsonArray = new JSONArray(myjsonstring);
and iterate through the array and read each values.
Your for loop looks fine.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
question = jsonObj.getString("question");
int no_score = jsonObj.getInt("no_score");
int yes_score = jsonObj.getInt("yes_score");
int category = jsonObj.getInt("category");
tvBoyGirl.setText(question);
}
This is what i do after all things
ListQuestion();
tvQuestionText.setText(questions.get(i));
imUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
question_counter++;
tvQuestionCounter.setText(String.valueOf(question_counter));
if (!questions.isEmpty()) {
tvQuestionText.setText(questions.get(i));
if (yes_Score1.get(i) == -1) {
score = score - 1;
} else {
score = score + yes_Score1.get(i);
}
System.out.println(score);
Log.d("yes_per", String.valueOf(score));
counter++;
if (counter == 25) {
calculation();
}
}
}
});
imDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i++;
question_counter++;
tvQuestionCounter.setText(String.valueOf(question_counter));
if (!questions.isEmpty()) {
tvQuestionText.setText(questions.get(i));
if (no_Score1.get(i) == -1) {
score = score - 1;
} else {
score = score + no_Score1.get(i);
}
Log.d("no_per", String.valueOf(score));
System.out.println(score);
counter++;
if (counter == 25) {
calculation();
}
}
}
});
}
Try this:
JSONArray jArray = new JSONArray(jsonString);
for(int i=0;i<jArray.length();i++)
{
JSONObject jObj = jArray.getJSONObject(i);
question = jObj.getString("question");
int no_score = jObj.getInt("no_score");
int yes_score = jObj.getInt("yes_score");
int category = jObj.getInt("category");
}

Android - get data from json

I have a api call that returns this json object:
{
"elenco": [
"folder 1",
"folder 2",
"folder 3"
],
"codice": "123456789"
}
and this is my piece of code that get the result:
protected void onPostExecute(JSONObject result) {
// Close progress dialog
Dialog.dismiss();
JSONObject jobj = null;
String codice_utente = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
codice_utente = jobj.getString("codice");
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
//This should fetch the elenco array
for (int i = 0; i < elenco_cartelle.length(); i++) {
JSONObject childJSONObject = null;
try {
childJSONObject = elenco_cartelle.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
}
How can I fetch the elenco part? I do not have a key to use, so how can I add every row in an ArrayList?
I tried to use a for but I have no idea about how to get the rows
Use JSONArray.getString() http://developer.android.com/reference/org/json/JSONArray.html#getString(int)
for (int i = 0; i < elenco_cartelle.length(); i++) {
String content = null;
try {
content = elenco_cartelle.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
You now have your content on content

Parsing Complex Json Object in android

i want to retrieve following filed from json object
From OriginLocation =>> CityCode, DepartureDate, DepartureTime
From DestinationLocation =>> CityCode, ArrivalTime, ArrivalDate
From Fare =>> OrigTotalFareAmt
From FlightDetails ==>> CabinClassCode, JourneyDuration
using one for loop
http://pastie.org/8563070#7
Try this.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("Key :" + key);
System.out.println("Value :" + data.getString(key));
}
} catch (Throwable e) {
try {
System.out.println("Key :" + key);
System.out.println("Value :" + data.getString(key));
} catch (Exception ee) {
}
e.printStackTrace();
}
}
}
}

JSON Parsing, structure assistance

JsonFactory f = new MappingJsonFactory();
JsonParser jp = f.createParser(res);
JsonToken current;
current = jp.nextToken();
if (current != JsonToken.START_OBJECT) {
System.out.println("Error: root should be object: quiting.");
return;
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
// move from field name to field value
current = jp.nextToken();
if (fieldName.equals("row")) {
if (current == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
JsonNode node = jp.readValueAsTree();
Log.e("KFF", node.get("col0").asText());
}
} else {
Log.e("KFF", "Error: records should be an array: skipping.");
jp.skipChildren();
}
} else {
Log.e("KFF", "Unprocessed property: " + fieldName);
jp.skipChildren();
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3DYHOO%26a%3D11%26b%3D10%26c%3D2011%26d%3D10%26e%3D10%26f%3D2013%26g%3Dd%22%3B&format=json&diagnostics=true&callback=
I'm currently using the above to parse JSON responses from the web (USING THE JACKSON JSON PARSING LIBARY) , however i'm at a loss at to how to parse nested json arrays such as the following, i.e. how to go down into each json array until 'row' and then be able to read each 'colx' eliminating 'unprocessed property'
Sorry about the horrendous quality of English in that, it's late and i'm at a loss in terms of describing it.
Something like this should work for you. Disclaimer - totally untested. This will put you in the right direction though.
// Assuming the json is in a String called jsonString
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArray = jsonObj.getJSONObject("query").getJSONObject("results").getJSONArray("row");
int arrayCount = jsonArray.length();
for(int i=0; i < arrayCount; i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
String col0 = jsonData.getString("col0");
String col1 = jsonData.getString("col1");
// etc, etc ...
// put those values in arrays or whatever here.
}

Accessing json contents in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending and Parsing JSON in Android
I have a JSON result in the following format which JSON Lint shows this as a Valid Response.
My question is: how do I accesss the content of "reportId0" value "164", "reportId1" value 157,reportId2 value 165, etc are all dynamic values?
My sample code for accessing value of properties.How to get Value reportid And add allvalue in Arraylist?
"properties": {
"link": "",
"approvalsReportCount": 3,
"reportName0": "srcapprovals",
"reportId0": 164,
"reportName1": "Approvals",
"reportId1": 157,
"requests_report_id": "163",
"requests_report_name": "EG approvals",
"reportName2": "fulfillment",
"reportId2": 165
}
This is the best way i found it to get ReportId value.
Below is My code
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
Log.v("key"," new report ID key " + currentDynamicKey);
Log.v("key"," new report ID key " + pro_object.getString(currentDynamicKey) );
}
}
you can use this
public ArrayList<String> getReportIds() {
boolean isContinue = true;
JSONObject json;
String tag = "reportId";
int i = 0;
ArrayList<String> repIdList = new ArrayList<String>();
JSONObject prop = null;
try {
json = new JSONObject("<your json string>");
prop = json.getJSONObject("properties");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (isContinue) {
String repId = "";
try {
repId = prop.getString(tag + i);
repIdList.add(repId);
i++;
} catch (JSONException e) {
isContinue = false;
e.printStackTrace();
}
}
return repIdList;
}
You can Try This!!
try {
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
Log.v("log_tag","json result Array : "+ jsonResultArray);
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
approvaldto_Key = new All_Approval_Key_dto();
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
approvaldto_Key.requestId = pro_object.getString(currentDynamicKey);
fetchrecursUserData.add(approvaldto_Key);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return fetchrecursUserData;
}
You can try below code
String serial= jsonObject.getJSONObject("response").getString("serialNumber");
or
JSONObject json;
try {
json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (JSONException e) {
Log.e("Podcast", "There was an error", e);
}

Categories

Resources