How to parse nested JSON object in android [closed] - android

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to parse the verse_nr and verse from the bellow JSON data.can anyone help me..
{"book":[{"book_ref":"Ps","book_name":"Psalms","book_nr":"19","chapter_nr":"16","chapter":{"8":{"verse_nr":"8","verse":"I have set the LORD always before me: because he is at my right hand, I shall not be moved."}}}],"direction":"LTR","type":"verse","version":"kjv"}

You'll need to use a JSON Parser library. Here's an example with org.json. parser.
JSONObject root = new JSONObject(inputJSON);
JSONObject chapter = root.getJSONArray("book")
.getJSONObject(0).getJSONObject("chapter");
JSONObject verse = chapter.getJSONObject(JSONObject.getNames(chapter)[0]);
Basically, you just chain the JSON getters till you reach the verse object. Once there, you can access the values with getString() as
System.out.println(verse.getString("verse_nr"));
System.out.println(verse.getString("verse"));
Output :
8
I have set the LORD always before me: because he is at my right hand, I shall not be moved.

You must iterate over it using JSONObject and JSONArray.
You can generate classes using: http://www.jsonschema2pojo.org/ Just make sure to check 'Json' as opposed to 'Json Schema' since this is the raw json. Then you can use gson to automatically turn this into the those generated classes. A guide on doing so:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
If this is coming from a server, I'd recommend using the wonderful Retrofit library which would allow you to do all the above with just a few lines of code; a tutorial of doing this can be found here: http://inaka.net/blog/2014/10/10/android-retrofit-rest-client/
Anyways if want to ignore making your life easier with the above solutions, to manually do this you'll do something like the following:
String jsonLiteral = /* your json remember to escape the double quotes */
JSONObject root = new JSONObject(jsonLiteral);
// Get Strings from a JSONObject as
String direction = root.getString("direction");
// You have a single element array, so you need to get that
JSONObject singleElement = root.getJSONArray("book").getJSONObject(0);
// Then you can Strings from it like direction above
String bookRef = singleElement.getString("book_ref");
You can also get a pretty output to inspect the json structure by using:
http://jsonformatter.curiousconcept.com/

Related

How to parse Local JSON (from Asset folder) for building Bible App in android [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am planning to build an app like BIBLE., For this I decided to use Local JSON to Parse the data.
Please share your ideas to get the data from Local JSon.
You can use Gson to ease your process of converting a JSON object to a Java Object and then you can easily access individual attributes of that Java class using getters and setters. Here is a small example:
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(
new FileReader("c:\\file.json"));
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
You can read / store local JSON as json objects directly in files or sqlite databases. Local or from a server working with json is not different
Just use GSon library to load and parse JSON file from assets. A good start could be here.

Parse several JSONOBject into an array in android [duplicate]

This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 7 years ago.
From the server I get a string with exactly the following format:
[{"valueOne", "341", "valueTwo": "1432"}, {"valueOne", "6483", "valueTwo": "3267"}]
I understand that it is two JSONObject into an array, but ..
Howparse this?
My intention is to have all the concatenated string values, like this:
Strings values = (341 + 1432 + 6483 + 3267);
I guess I must first convert the string that I have received from the server to JSONObject, but do not know how to continue.
In this example there are two JSONObjects, but sometimes may contain three or more.
Many times I get values from JSONObjects values, but I have never seen in this case. I searched for information but can not find a solution that is useful to me.
I appreciate the help
greetings!
JsonArray jArray= <your parsed array>;
for(int i=0;i<=jArray.lenght()-1;i++)
{
String valueOne=jArray.getJsonObject(i).getString("ValueOne");
String valueTwo=jArray.getJsonObject(i).getString("ValueTwo");
}
you can do whatever you want with the values.

What is a concrete example of Android app functionality that uses HashMap? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner in Android, and understand only very basically that HashMap class enables key/value pairs. But how does this translate into actually using this in an Android app? Could someone provide a simple, plain English example of what case you might want to use HashMap in an app? I cannot imagine a case where I might need it. Make up an Android app idea, if needed. Thanks in advance.
I am looking for a "big picture" analysis that will give some examples where you might use HashMap with certain Android functionalities you are trying to implement.
HashMap or Map interface is not new on android, This is Java Collections framework.
Java collection are meant to be used in several cases to hold data and contain 3 interfaces:
List - Basically simple list,or linked list implementations
Set - The same as list but won't hold 2 equal obejcts(You need to implement you own equals and hashcode)
Map - as you said key value pair.
Uses:
List - For anything, just to hold data
Set - For list of data that we want that all of the items will be unique.
Map - Key value and the most common example is the use for DB items, or something with ids.. for example:
bookId, Book.. I that case you can take the object by id.. This is the most common
I attached link for Java collection tutorial.. It is very important framework that you have to know if you are going to develop java/android
http://tutorials.jenkov.com/java-collections/index.html
Hope that helps
We could use HashMap to keep a list of employess together with their respective salaries.
We can do:
HashMap<String, Float> emplMap = new HashMap<String, Float>();
emplMap.put("fred", 1.000);
for(String name : emplMap.keySet()) {
System.out.print(name + "'s salary is" + emplMap.get(name));
}
Should print
"fred's salary 1.000"

Substring in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi guys I'm newbie in android dev.. can you help me with this one? I am trying to get the filename in string. I know that I need to substring it but I failed to get the right output. For example I have the string value of:
{"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
and I want to get only the filename which is "23476-love-823873.jpg" How can I do that? Thanks for helping.
You've got structured data there, so you shouldn't do this blindly with a substring. Instead, you can parse your string as JSON and then access the appropriate property of the new object. There's an Android JSON library that you can import from org.json. Specifically, you'll want to use the parser here: http://developer.android.com/reference/org/json/JSONTokener.html
Given:
yourstring= {"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
Try this Code:
int startindex,endindex;
startindex=indexOf(':');
endindex=indexOf(',');
String filename= yourstring.substring(startindex,endindex);
It looks like a structured object( HashMap, NameValuePair, JSON etc.).
Anyway, If its a String,
String mString = "{\"Filename\":\"23476-love-823873.jpg\",\"ChunkId\":1,\"ChunkLength\":201929,\"FileLength\":12122}";
if(mString.contains("Filename")){
int start=mString.indexOf("Filename")+11;// If file name is not at beginning, have to do like this.
int end=mString.indexOf(",", start)-1;//-1 for excluding a double code
String filename=mString.substring(start, end);
}
then if that string is json response and you are sure that you will consistently get that string format then it is applicable to use the approach given by #Abhishek. See my sample below, same as what he gave.(a very little revision).
String sample = "{"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}";
Log.d("string", sample);
int startindex,endindex;
startindex = sample.indexOf(':');
endindex = sample.indexOf(',');
String filename= sample.substring(startindex + 1,endindex);
Log.d("result", filename);
your log will be like this:
string {"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
result "23476-love-823873.jpg"
It's look like a JSON string, there are many ways for you to parse it.
Refer to same question on SO: Sending and Parsing JSON Objects
The standard approach will be using a JSON library to de-serialize the String into a Java object or Map and then get the property value. If it is too heavy, you can use Regular Expression.

How to extract the string variable in android? [duplicate]

This question already has an answer here:
How to extract this string variable in android?
(1 answer)
Closed 9 years ago.
String test=["1","Low-level programming language",true]
Here i want to extract this string value and as i need to get only second value like "Low-level programming language".How to get this value using string functions in android?
Per your comment, I'm assuming that you have a single string that contains the entire text (including the brackets). In general, splitting comma-separated values is a fairly tricky process. For your specific string, though, it's kind of easy:
String test = "[\"1\",\"Low-level programming language\",true]";
String[] pieces = test.split(",");
String middle = pieces[1];
// now strip out the quotes:
middle = middle.substring(1, middle.length() - 1);
In general, you might want to look at using a general CSV parser like Apache Commons CSV or openCSV.
Alternatively, if this is JSON data (which looks more likely than CSV), take a look at using one of the Java JSON libraries listed here (scroll down the page to see the list).

Categories

Resources