get object from Object in json android - android

How to Get object from verticals from json android.
I have got the vertical object.
JSONObject obj = new JSONObject(loadJSONFromAsset());
Log.d(String.valueOf(obj),"obj");
want other 4 which are
health care
environmental care
agricultural product
consumer product

You can get JSON Objects from main object as follow:
1- Create Model classes for your JSON string. You can either use jsonschema2pojo or Android Plugins to create models classes for you.
2- Then follow this code
Response response = new Gson().fromJson(loadJSONFromAsset(), Response.class);
List<CartridgesItemItem> cartridges = response.getVerticals().getHealthCare().getCartridges();
List<PackingRollsItemItem> packingRolls = response.getVerticals().getHealthCare().getPackingRolls();
List<SterilizersItemItem> sterilizers = response.getVerticals().getHealthCare().getSterilizers();
where Response is my main model class created.
====================================================================
====================================================================
If you want to install plugin in Android Studio for converting JSON to model classes follow these steps:
1- You can go to Android Studio settings -> Plugins
2- search for RoboPOJOGenerator and install it
3- Then click on any package/folder on left side of your android studio
Select package -> new -> Generate POJO from JSON
See here
4- Paste your Json string and Write name for your main class
See here
5- Use above code mention in 2nd point for getting your string as model class (Response)
Note: you might need to add this dependency in build.gradle app
//GSON
implementation 'com.google.code.gson:gson:2.8.9'
Hope this helps !!

You can easily create Model class with response:
https://www.jsonschema2pojo.org/
check this website. If you can not achieve your task then use any android studio plugin to create model classes.

The best way to do it would be to create a POJO class. The alternate solution to this would be to get Object from JSON and use it in your Model Object
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONObject healthCare = obj.optJSONObject("Health Care")
This is just another way to get json object from JSON. POJO classes should be the way it is done as mentioned in the answer by #Ali Ahmed

Related

android retrofit ,post whole Pojo using this format

I want to post this kind of request in retrofit2 so if someone have idea about it then it would be great help of mine.
reqObject={"task":"singleUser","taskData":{"userID":"1"}}
Yes, good Question It is some what not understandable for Beginner.
So I combining some Answers for you.
first step
make your Json -> model class (or POJO class)
From GsonFormattor plugin
This plug-in convert your Json to Model class
Pojo genrator
Go to this link , copy and paste Your Json and simply make your model class.
OK , we completed our first step
Second Step
Set all value to your Model class what You want from getter() setter().
Retrofit having #Body annotation that use in your case
#POST("/jayson")
FooResponse postJson(#Body MyGsonModelClass body);
Where MyGsonModelClass is class we made from first step.

How to post JSON Array to server in android via retrofit2?

How do I post a json array with retrofit2?
For example,
http://www.test.com/post/listparam=[{id=1,name="A"},{id=2,name="B"}]
If you want to pass any json,pass pojo class or bean class
For Example if your json is like this
{
"main":{"id":"1","name":"A"}
}
Then paste your json string in jsonshematopojo.org,
In source type click JSON radio button,In Annotation style select Gson and also click include constructers(You can download your generated bean classes by clicking Zip button).Then instead of passing json pass like this
new Example(new Main(id,name));
Instead of declaring String parameter in interface declare Example(Your main bean class name

Is there any way to directly handle json in android/java without convert [duplicate]

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:
String json = "{ data: { data2 : { value : 'hello'}}}";
...
// Somehow we managed to convert json to jsonObject
...
String result = jsonObject.getAsString("data.data2.value");
System.out.println(result);
I expect to get "hello" as output.
So far, the fastest way I have found is using Gson:
jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();
It's not actually easy to write and read. Is there something faster?
I've just unexpectedly found very interesting project: JSON Path
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
With this library you can do what you are requesting even easier, then my previous suggestion:
String hello = JsonPath.read(json, "$.data.data2.value");
System.out.println(hello); //prints hello
Hope this might be helpful either.
While not exactly the same, Jackson has Tree Model representation similar to Gson:
JsonNode root = objectMapper.readTree(jsonInput);
return root.get("data").get("data2").get("value").asText();
so you need to traverse it step by step.
EDIT (August 2015)
There actually is now (since Jackson 2.3) support for JSON Pointer expressions with Jackson. So you could alternatively use:
return root.at("/data/data2/value").asText();
First of all, I would recommend consider JSON object binding.
But in case if you get arbitrary JSON objects and you would like process them in the way you described, I would suggest combine Jackson JSON processor along with Apache's Commons Beanutils.
The idea is the following: Jackson by default process all JSON's as java.util.Map instances, meanwhile Commons Beanutils simplifies property access for objects, including arrays and Map supports.
So you may use it something like this:
//actually it is a Map instance with maps-fields within
Object jsonObj = objectMapper.readValue(json, Object.class);
Object hello = PropertyUtils.getProperty(jsonObj, "data.data2.value")
System.out.println(hello); //prints hello
You can use org.json
String json = "{ data: { data2 : { value : 'hello'}}}";
org.json.JSONObject obj = new org.json.JSONObject(json);
System.out.println(obj.query("/data/data2/value"));
I think no way.
Consider a java class
class Student {
Subject subject = new Subject();
}
class Subject {
String name;
}
Here if we want to access subject name then
Student stud = new Student();
stud.subject.name;
We cant access name directly, if so then we will not get correct subject name. Like here:
jsonObject.getAsJsonObject("data")
.getAsJsonObject()
.get("data2")
.getAsJsonObject("value")
.getAsString();
If you want to use same like java object then use
ClassName classObject = new Gson().fromJson(JsonString, ClassName.class);
ClassName must have all fields to match jsonstring. If you have a jsonobject inside a jsonobject then you have to create separate class like I'm doing in Student and Subject class.
Using Java JSON API 1.1.x (javax.json) one can make use of new JavaPointer interface. Instance implementing this interface can be considered to some extend as kind of XPath expression analog (see RFC-6901 for details). So in your case you could write this:
import javax.json.*;
//...
var jp = Json.createPointer("/data/data2/value");
System.out.println(jp.getValue(jsonObject));
In 1.1.4 version of JSON there's also nice addition to JsonStructure interface (which is implemented by JsonObject and JsonArray), namely getValue(String jsonPointer). So it all comes down to this simple one-liner:
System.out.println(jsonObject.getValue("/data/data2/value"));

Create standalone object from realm result in android

I am new to android realm.
I am using follwing code to get product object from realm.
ProductModel prodObj = realm.where(ProductModel.class).equalTo("product_id","12").findFirst();
How can i create standalone copy of prodObj?
I want to update some field's value that should not affect in realm database. I don't want to set it manually with setters method because model class contains too many fields. Is there any easy way to create standalone copy of prodObj?
Since 0.87.0
Added Realm.copyFromRealm() for creating detached copies of Realm objects (#931).
Realm only has a copyToRealm method and not a copyFromRealm method. Currently, there is a number of restriction to model classes (see https://realm.io/docs/java/latest/#objects) but we are investigating and experimenting how to lift these.
We have an open issue about exactly what you are asking: https://github.com/realm/realm-java/issues/931. But for the time being, you will have to copy our objects manually.
In case anyone wondered like me how we can implement this copyFromRealm(), this is how it works:
ProductModel prodObj = realm.where(ProductModel.class)
.equalTo("product_id", "12")
.findFirst();
ProductModel prodObjCopy = realm.copyFromRealm(prodObj);
You can serialize an object into a JSON string and deserialize into a standalone object by Jackson like:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(yourObject);
objectMapper.readValue(json, YourModel.class);
GSON might not work because it doesn't support getter/setter when it makes a JSON.
I know it's a horrible solution.
But it might be the only way yet.

How to start an android project coders view

I've been searching for the past week on how to develop an android project, read some on android developers page and on other websites like here, but no text was complete.
i have this project - i'm a php developer not a java, but could understand a bit about java lately.
the thing is i want to develop an android app using my website, i did output a json type data from my website, and gonna use them on the android app, i did the async request on android and could read the data form the website but :
first question: how to parse the json data correctly and convert it to array on android, i did that through:
Iterator<String> itr = myObject.keys();
while (itr.hasNext()) {
...
i don't know if that's the correct way, when i try to convert my json object to array, it gives me type mismatch.
second and more importantly:
how can create a "Block" like facebook posts style, or twitter style blocks, you know - blocks of json data, is it a linearlayout ? what do i call it ? and how can i add it to the UI dynamically, cuz these blocks are pulled from the website json data. so they are arrays...of blocks..
i'm kinda confused still, i need a start point.
Thank you!
excellent tutorial for beginners for android development
http://thenewboston.org/list.php?cat=6
and for your first question - how to parse json data correctly,
you can try using gson to convert the json data into POJO
otherwise you'd have to do myObject.opt(key) to make sure it is there
First question: you should use a library to parse JSON, it's simpler that way. Try gson. You should create a class, which holds the parsed object, like:
public class Taxi implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("idTaxi")
private Integer idTaxi;
#SerializedName("name")
private String name;
//getter, setters, constructor, etc
}
Then when you get the JSON object, you can parse it:
Gson gson = new Gson();
Reader reader = new InputStreamReader(SOURCE_STREAM);
Taxi[] response = gson.fromJson(reader, Taxi[].class);
Second question: i think a ListView would be good for you. You can read a full tutorial about it here

Categories

Resources