how to parse something like this in JSON ?
{"nodes":
{"0":
{"node":{"id":"13970","name_ar":"\u0623\u062f\u0647\u0645","name_en":"Adham","bio_ar":""}},
"1":
{"node":{"id":"14033","name_ar":"aa","name_en":"Ahmed Shaalan","bio_ar":""}}}
Its not an array its more than one object, any help please ?
You can retrieve them using JSONObject. This is a very simple example, and only parses the id out of one node:
JSONObject object = new JSONObject(myJsonString);
JSONObject nodes = object.getJSONObject("nodes");
JSONObject zero = nodes.getJSONObject("0");
JSONObject myNode = zero.getJSONObject("node");
String id myNode = myNode.getString("id");
Android contains native JSON parser - it is good for small amount of data (look into package org.json ) . If you have more data to parse, some pull parser like GSON will be better.
You need to create first a class with all the variables inside the JSON. Something like this:
import java.util.HashMap;
public class NodesClass { // Create a new class called NodesClass
public Nodes nodes; // Create a new public class
public class Nodes {
public HashMap<String, InnerObject> nodes;
}
public class InnerObject {
public Node node;
public class Node {
public int id;
public String name_ar, name_en, bio_ar;
}
}
}
Ant then you need to retrieve the data. E.g something like this:
NodesClass ndes = new Gson().fromJson(stringNodes, NodesClass.class);
int[] id = new int[11];
for (int numNodes = 0; numNodes < maxNumNodes; numNodes++)
{
try {
id[numNodes] = ndes.nodes.get(String.valueOf(numNodes)).node.id;
} catch (NullPointerException n) { break; }
}
I hope it help you.
Use org.json.JSONObject class:
jObject = new JSONObject(jString);
JSONObject nodesObject = jObject.getJSONObject("nodes");
ArrayList<JSONObject> objects = new ArrayList<JSONObject>();
for( int i=0; i<10; i++)
{
objects.add(nodesObject.getJSONObject(""+i);
}
String name = objects.get(0).getJSONObject("node").getString("name_ar");
...
Related
My Json file is
{"code":0,"datas":[{"id":0,"target_id":0},{"id":1,"target_id":0
}................]}
And what I wrote is..
// String data;
// data has the Json as String
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(data);
JsonArray memberArray = (JsonArray) object.get("datas");
JsonObject object1= (JsonObject) memberArray.get(0);
dataParsed = object1.get("id").getAsString();
// wanted print 1
And it's not working..
As I guess it's something different with normal Json on Internet.
I thought "code" : 0 is the problem
I want to know how to seperate this json code / data and get id and target id String
Your JSON contains an integer ("code") plus an array. the array itself contains a number of JSON objects. First, extract a JSON object and an array, then extract JSON objects from the array.
My solution for storing these data is based on object-oriented programming. Create a Java object with two variables called DataObject. An integer for "code" and a list of another Java object called IdPair for storing "id" and "target_id". First, define the classes. IdPair object class:
public class IdPair {
int id;
int target_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTarget_id() {
return target_id;
}
public void setTarget_id(int target_id) {
this.target_id = target_id;
}
}
DataObject class:
public class DataObject {
private int code;
private List<IdPair> idPairs;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public List<IdPair> getIdPairs() {
return idPairs;
}
public void setIdPairs(List<IdPair> idPairs) {
this.idPairs = idPairs;
}
}
then start extracting data from your json:
DataObject dataObject = new dataObject(); // init object
JSONObject jsonObject = new JSONObject(data); // whole json is an object! (data is your json)
int code = jsonObject.optInt("code"); // get code from main json
dataObject.setCode(code); // set code to our object
List<IdPair> pairs = new ArrayList<>(); // init list of id pairs
JSONArray datas = jsonObject.optJSONArray("datas"); // get json array from main json
IdPair pair = null; // define idPairs object
for (int i=0; i<datas.length() ; i++){ // jasonArray loop
JSONObject object = new JSONObject(datas(i)); // each jsonObject in the jsonArray
pair = new IdPair();// init idPair
int id = object.optInt("id"); // get the object id
int targetId = object.optInt("target_id"); // get the object target_id
// set values to our object
pair.setId(id);
pair.setTarget_id(targetId);
//add object to list
pairs.add(pair);
}
// your dataObject is now filled with JSON data
Note: this is a general solution. For example, you could use a HashMap instead of IdPair object.
Here you can do the following code for obtaining id and target_id values from your json:
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(new String(Files.readAllBytes(Paths.get("test.json"))));
JsonArray memberArray = (JsonArray) object.get("datas");
for (JsonElement jsonElement : memberArray) {
System.out.println(
String.format("Id : %d TId: %d",
jsonElement.getAsJsonObject().get("id").getAsInt(),
jsonElement.getAsJsonObject().get("target_id").getAsInt()));
}
Output is:
Id : 0 TId: 0
Id : 1 TId: 0
I have a JSON that contains the names of Countries, their states and cities of those states. Here is the json.
I am able to get all the countries but I can't figure out how to get the states based on the selected country and then cities based on the selected state.
Here is how I got the countries.enter code here
First to load the file from assets:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Contries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Then to load the countries into an ArrayList.
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Then this line finally:
loadCountries("Countries", "CountryName", countries);
After I have selected a country, I want to load its states. maybe something like this:
loadCountries("Pakistan", "StateName", states);
and then:
loadCountries("Islamabad Capital Territory", "CityName", cities);
Any help is greatly appreciated.
Working with JSON can be error-prone. Why don't we model objects around your data and we can do something a little more clearer.
Overview.
Lets' Model your objects
Let's Deserialize your raw json into "Objects"
Then we can "query" our modelled objects!
Step 1 - Modelling.
Note I'm not including constructors, getters, setters and any other boiler plate.
public class Country {
private List<State> states;
private String name;
public Optional<State> getStateByName(String name) {
return States.stream().filter(state -> state.getName().equals(name)).findFirst();
}
}
public class State {
private List<String> cities;
private String name;
public Optional<String> getCityByName(String name) {
return cities.stream().filter(city -> city.equals(name)).findFirst();
}
}
public class CountryDataProvider {
private List<Country> countries;
public CountryDataProvider(String rawData) {
// parse your json to create a List of object Country (tip: Use something like Jackson or Gson to do this for you).
// Ref to part 2
}
public Optional<Country> getCountryByName(String name) {
return countries.stream().filter(country -> country.getName().equals(name)).findFirst();
}
}
Step 2 - Deserialize.
This is a broad topic and To be honest there is a lot of libraries that will do it better and they are really easy to add to your project. Here are a few:
Jackson https://github.com/FasterXML/jackson
GSON https://github.com/google/gson <- My pick.
Step 3 - Query
From here you can do what ever you want
countryData = new CountryDataProvider(data);
Optional<List<String>> countriesInPunjab = countryData.getCountryByName("Pakistan")
.map(country -> country.getStateByName("Punjab")
.map(state -> state.getCities()); // would give you all the cities in Punjab, Pakistan.
The code I have given in my example does use functional and Optional interfaces (in Java 8). Let me know if you want them rewritten in a less functional way.
Here is another solution, not very CPU friendly but it works:
First use this method to get a list of countries:
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);
// m_jArry;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Call this method like this:
loadCountries("Countries", "CountryName", countries);
Then use the following method to load the States and Cities.
private void getCitiesByState(String countryName, String stateName)
{
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray countriesArray = json.getJSONArray("Countries");
for(int i = 0; i < countriesArray.length(); i++)
{
JSONObject countryJSON = countriesArray.getJSONObject(i);
if(countryJSON.getString("CountryName").equals(countryName))
{
JSONArray statesArray = countryJSON.getJSONArray("States");
states.clear();
for(int j = 0; j < statesArray.length(); j++)
{
JSONObject statesJSON = statesArray.getJSONObject(j);
states.add(statesJSON.getString("StateName"));
if(statesJSON.getString("StateName").equals(stateName))
{
JSONArray citiesarray = statesJSON.getJSONArray("Cities");
cities.clear();
for(int k = 0; k < citiesarray.length(); k++)
{
cities.add(citiesarray.getString(k));
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is how my JSON looks like and I have to parse the JSON, how can this be done using GSON
{
"data": {
"a": {
"abc": {
"c": "d"
}
}
}
}
In which "a" is dynamic key which may vary from time to time. I am unable to find a solution right now
Model
public class Model {
private HashMap<String, String> data;
public Model() {
}
}
Convert json string to Hashmap using Gson & prepare data from hashmap
Gson gson = new Gson();
Type typeHashMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(YOUR_JSON, typeHashMap);
Set<Map.Entry<String, String>> entrySet = data.entrySet();
Iterator iterator = entrySet.iterator ();
for(int j = 0; j < entrySet.size(); j++) {
try {
Map.Entry entry = (Map.Entry) iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
//Add it to your list
}
catch(NoSuchElementException e) {
e.printStackTrace();
}
break;
}
I am not sure if internal part abc is known to you or not. If it is known to you then you can surely do it with GSON. You have to create the class for the inner known object as below:
public class ABC {
public C abc;}
Then create the Class for C:
public class C {
public String c;}
Then just pass the ABC class as the hashmap value as below:
public HashMap<String, ABC> a;
I got this JsonObject from JsonObjectRequest (im using Volley). How can I cast to Object?
{
"objects":
[
{"name":"German","id":5,},
{"name":"Cecilia","id":6,},
{"name":"Melina","id":7,},
{"name":"Karina","id":8,},
{"name":"Marcos","id":9,}
]
}
public class Invitados {
private String name;
private int id;
public Invitados(){}
public Invitados(String name, int id){
this.name=name;
this.id=id;
}
}
Thanks
Use Gson library (as you included in tags to this question) create Gson object and use its fromJson() method
You can do something like this
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
Invitados inv = new Invitados(obj.get("name").getAsString(),obj.get("id").getAsInt());
//Doing something...
}
I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.
UPDATE - SOLUTION
Here is what I ended up doing to solve the issue.
Object in ArrayList:
public class ListItem {
private long _masterId;
private String _name;
private long _category;
public ListItem(long masterId, String name, long category) {
_masterId = masterId;
_name = name;
_category = category;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Id", _masterId);
obj.put("Name", _name);
obj.put("Category", _category);
} catch (JSONException e) {
trace("DefaultListItem.toString JSONException: "+e.getMessage());
}
return obj;
}
}
Here is how I converted it:
ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
jsonArray.put(myCustomList.get(i).getJSONObject());
}
And the output:
[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
References:
jsonarray constructor:
http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
collection:
http://developer.android.com/reference/java/util/Collection.html
Use Gson library to convert ArrayList to JsonArray.
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:
Gson gson = new Gson();
String listString = gson.toJson(
targetList,
new TypeToken<ArrayList<targetListItem>>() {}.getType());
JSONArray jsonArray = new JSONArray(listString);
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {
JSONObject jResult = new JSONObject();// main object
JSONArray jArray = new JSONArray();// /ItemDetail jsonArray
for (int i = 0; i < list.size(); i++) {
JSONObject jGroup = new JSONObject();// /sub Object
try {
jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
jGroup.put("ID", list.get(i).get("id"));
jGroup.put("Name", list.get(i).get("name"));
jGroup.put("Category", list.get(i).get("category"));
jArray.put(jGroup);
// /itemDetail Name is JsonArray Name
jResult.put("itemDetail", jArray);
return jResult;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
With kotlin and Gson we can do it more easily:
First, add Gson dependency:
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
Create a separate kotlin file, add the following methods
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
fun <T> Gson.convertToJsonString(t: T): String {
return toJson(t).toString()
}
fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
return try {
fromJson(jsonString, cls)
} catch (e: Exception) {
null
}
}
inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)
Note: Do not add declare class, just add these methods, everything will work fine.
Now to call:
create a reference of gson:
val gson=Gson()
To convert array to json string, call:
val jsonString=gson.convertToJsonString(arrayList)
To get array from json string, call:
val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)
To convert a model to json string, call:
val jsonString=gson.convertToJsonString(model)
To convert json string to model, call:
val model=gson.convertToModel(jsonString, YourModelClassName::class.java)
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList to JsonArray
JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better ..
Hope this helps.
Cheers. :D
Here is a solution with jackson:
You could use the ObjectMapper to receive a JSON String and then convert the string to a JSONArray.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
List<CustomObject> myList = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(myList);
JSONArray jsonArray = new JSONArray(jsonString);
Improving on OP's answer when there are a lot of fields.
could cut down some code with field enumeration ... ( but know that reflection is slower.)
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
Field[] fields = ListItem.class.getDeclaredFields();
for (Field f : fields) {
try {
obj.put(f.getName(), f.get(ListItem.this));
} catch (JSONException | IllegalAccessException e) {
}
}
return obj;
}