How to get name from this JSON data using JAVA - java

[
{
"orderDetails": [
{
"account_name": "akhil_kotak",
}
]
}
]
How to get the account name from this json, i tried doing this
String response = new String(responseBody);
//ON SUCCESS GETS JSON Object
JSONArray array = new JSONArray(response);
JSONObject obj =
array.getJSONObject(0).getJSONArray("orderDetails").getJSONObject(0);
txt_accountName.setText(obj.getString("account_name"));
If anyone can help, that would be awesome.
Thanks

Your JSON is invalid.
You can change to this.
[
{
"orderDetails": [
{
"account_name": "akhil_kotak"
}
]
}
]
Just change "account_name": "akhil_kotak" , to "account_name": "akhil_kotak" .
Just remove the comma in your JSON .
Try this .
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray orderDetails = jsonObject.getJSONArray("orderDetails");
for (int j = 0; j < orderDetails.length(); j++) {
JSONObject jsonObject2 = orderDetails.getJSONObject(j);
String account_name = jsonObject2.getString("account_name");
txt_accountName.setText(account_name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

if you are using Jackson 2 .. below works
String jsonString = "[{\"orderDetails\": [{\"account_name\": \"akhil_kotak\",}]}]";
ObjectMapper mapper = new ObjectMapper();
JsonNode jnNode= mapper.readTree(jsonString);
Sting accName=jnNode.get("orderDetails").get("account_name").asText();
}

Your JSON is invalid. Remove comma! then:
Create a set of calsses and use Gson!
Add this line to dependencies in your build.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.8.2' //add this line
}
Crate a set of classes:
class SomeListItem {
#SerializedName("orderDetails")
public List<InnerListItem> mOrderDetails;
}
class InnerListItem {
#SerializedName("account_name")
public String mAccountName;
}
And use them like this:
String jsonOutput = "[\n" +
" {\n" +
" \"orderDetails\": [\n" +
" {\n" +
" \"account_name\": \"akhil_kotak\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"]";
Gson gson = new Gson();
Type listType = new TypeToken<List<SomeListItem>>(){}.getType();
List<SomeListItem> parsedJson = gson.fromJson(jsonOutput, listType);
String accountName = parsedJson.get(0).mOrderDetails.get(0).mAccountName;

try this. i am using org.json.simple library.
String str="[{\"orderDetails\": [{\"account_name\": \"akhil_kotak\",}]}]";
JSONParser parser=new JSONParser();
JSONArray array=(JSONArray) parser.parse(str);
JSONObject obj=(JSONObject) array.get(0);
JSONArray nestedArray=(JSONArray) obj.get("orderDetails");
System.out.println("output: "+nestedArray.get(0).get("account_name"));
it's working fine.

Related

Showing data when multiple objects exist in JSON URL

I have a JSON File, showing the following:
{
"version": 2,
"locations": [{
"id": "750",
"geo": {
"name": "Lord Howe Island",
"state": "Lord Howe Island",
"country": {
"id": "au",
"name": "Australia"
},
"latitude": -31.557,
"longitude": 159.086
},
"astronomy": {
"objects": [{
"name": "moon",
"days": [{
"date": "2018-09-05",
"events": [],
"moonphase": "waningcrescent"
}]
}]
}
}]
}
I am attempting to show in a TextView the following fields:
name "Lord Howe Island"
latitude "-31.557"
longitude "159.086"
moonphase "waningcrescent"
I have tried the following:
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + JO.get("moonphase") + "\n";
}
But unfortunately I do not receive any results.
What am I doing wrong? Thanks very much for any help.
Edit - Full Code for assistance.
public class fetchData extends AsyncTask<Void, Void, Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo = JO.getJSONObject("geo");
JSONObject astronomy = JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.fetcheddata.setText(this.data);
}
}
Try this
JSONObject data=new JSONObject(data);
JSONArray JA = data.getJSONArray("locations");
for (int i = 0; i < JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
JSONObject geo=JO.getJSONObject("geo");
JSONObject astronomy=JO.getJSONObject("astronomy");
singleParsed = "Name:" + geo.get("name") + "\n" +
"Latitude:" + JO.get("latitude") + "\n" +
"Longitude:" + JO.get("longitude") + "\n" +
"Phase: " + astronomy.get("moonphase") + "\n";
instead of parsing JSON on your own use gson
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
Json to Java POJO
From above you can get as Bean class just use it to parse your Json.Using POJO to parse json is easy and less vulnerable to error/exception.
For your Json i tried getting the bean object and tried parsing.
And your code will also be more readable:
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("example.com"); //Replace with API URL
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data + line;
}
Gson gson= new Gson();
YourBeanClass yourBeanClass gson.fromJson(jsonString,YourBeanClass.class)
//get and set all your data here from your bean
String country=yourBeanClass.getCountry()
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Your json parsing is wrong.First of all there is just one object in your json array there is no need of the for loop. You can access it directly using 0th index.
Second
JSONObject JO = (JSONObject) JA.get(i);
This line just gave you the 1st json object inside the array. You have to do one more step to fetch the name.
JSONObject geo=JO.getJSONObject("geo");
Now fetch the name from geo object.
"Name:" + geo.getString("name") + "\n"
Also remember your moonphase string is part of different array. So you need to parse that accordingly
You have to get value of the type defined in your json.For eg. for getting string type it will be
jsonObject.getString("key");
for integer it will be
jsonObject.getInt("key")

Append or remove data from JSON

The result i want to get:
[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
To add new data to JSON i tried this:
String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
But i don't get a proper result.
And how to remove a JSON data depend on the value of the ID ?
Thank's.
To build a fresh JSONArray you can use below codes:
try {
JSONArray jsonArray = new JSONArray();
// Object 1
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", 1);
jsonObject1.put("name", "example1");
jsonObject1.put("description", "An example");
// Object 2
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", 2);
jsonObject2.put("name", "example2");
jsonObject2.put("description", "Just another example");
// Add Object 1 & 2 JSONArray
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]
To add new JSONObject into existing JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2, "name":"example2","description":"Just another example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
// Object 3
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("id", 3);
jsonObject3.put("name", "example3");
jsonObject3.put("description", "Third example");
// Add Object 3 JSONArray
jsonArray.put(jsonObject3);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
To remove JSONObject from JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2,"name":"example2","description":"Just another example"},
// {"id":3,"name":"example3","description":"Third example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
Log.d("JSON", "JSON before Remove: " + jsonArray.toString());
// Remove Object id = 2
int removeId = 2;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
if (object.has("id") && !object.isNull("id")) {
int id = object.getInt("id");
if (id == removeId)
{
jsonArray.remove(i);
break;
}
}
}
Log.d("JSON", "JSON After Remove: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]
Hope this will help you.
The root object of the json is an array so you should use a JSONArray, not a JSONObject.
String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);

Parsing JSON string in Java android

I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}

Can't decode Json array values?

How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.

Using Java to decode JSON array of objects

I have JSON as follows:
[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
It is an array of objects.
I need to parse it using Java. I am using the library at :
http://code.google.com/p/json-simple/downloads/list
Example 1 at this link approximates what I require:
http://code.google.com/p/json-simple/wiki/DecodingExamples
I have the following code:
/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)
Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
try {
jsonObj = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2: " + jsonObj.get("1"));
} catch (JSONException e) {
e.printStackTrace();
}
}
I am getting the following exception:
java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
Can someone please help?
Thanks.
Instead of casting your Object to JSONArray, you should do it like this:
JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
mJsonObject.getString("0");
mJsonObject.getString("id");
mJsonObject.getString("1");
mJsonObject.getString("name");
}

Categories

Resources