Convert object to JSON in Android
Most people are using gson : check this
Gson gson = new Gson();
String json = gson.toJson(myObj);
How to convert a Java Object to a JSONObject?
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
Converting Java objects to JSON with Jackson
To convert your object
in JSON with Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
conversion from string to JSON object Android
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
convert Jsonobject to JsonArray in android
Whatever you get in JsonObject
, just put
that object in JsonArray
:
JsonArray jsonArray = new JsonArray();
jsonArray.put(jsonObject);
// jsonObject is like { "Name": "Prashant", "RollNo":"10"}
How to convert jsonString to JSONObject in Java
Using org.json library:
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
How to Convert object of arraylist to JsonObject in android?
you first declare arrays :
String[] name ={"yousuf" , "Mohammed" , "Ali" , "Hamood" , "Alex"};
String[] emails = {"yousuf@dd" , "Mohammed@dd" , "Ali@dd" , "Hamood@dd" , "Alex@dd"};
any arrays with data ,
then you create JSONArray
JSONArray array = new JSONArray();
then you make loop to add objects to the array :
for (int i =0; (i < name.length) && (i < emails.length) ; i++ ) {
JSONObject object = new JSONObject();
try {
object.put("name", name[i]);
object.put("email" , emails[i]);
array.put(object);
}catch (JSONException e) {
e.printStackTrace();
}
}
then you can print the results in the console :
Log.d("Json is " , array.toString());
you will get the result like this :
[{"name":"yousuf","email":"yousuf@dd"},{"name":"Mohammed","email":"Mohammed@dd"},{"name":"Ali","email":"Ali@dd"},{"name":"Hamood","email":"Hamood@dd"},{"name":"Alex","email":"Alex@dd"}]
but you can format it by :
Json formatter and validator
and you'll have nice look to the data :
here is the whole code:
public void getDataInJsonFormat (){
String[] name ={"yousuf" , "Mohammed" , "Ali" , "Hamood" , "Alex"};
String[] emails = {"yousuf@dd" , "Mohammed@dd" , "Ali@dd" , "Hamood@dd" , "Alex@dd"};
JSONArray array = new JSONArray();
for (int i =0; (i < name.length) && (i < emails.length) ; i++ ) {
JSONObject object = new JSONObject();
try {
object.put("name", name[i]);
object.put("email" , emails[i]);
array.put(object);
}catch (JSONException e) {
e.printStackTrace();
}
}
Log.d("Json is " , array.toString());
}
How to convert an Kotlin array of objects into json array with preserving access key names?
It's an ugly request, and you might be able to resolve it with an ugly solution :)
I wouldn't suggest this for anything serious, large, or anything that requires some hard and complex maintenance, but if this object will stay that simple (one int and two strings, non-nullable fields) and won't change a lot, you can do it manually:
class RailPoint(
var railPointId: Int,
var startTime: String,
var endTime: String
)
val rails = listOf(
RailPoint(1, "", "2021-10-19 07:37:19"),
RailPoint(2, "2021-10-19 07:33:37", "2021-10-19 07:35:20"),
)
fun toJson(rails: List<RailPoint>): String {
val sb = StringBuilder()
rails.forEachIndexed { index, railPoint ->
sb.append("\"railPoint[$index][railPointId]\": ${railPoint.railPointId},")
sb.append("\"railPoint[$index][startTime]\": \"${railPoint.startTime}\",")
sb.append("\"railPoint[$index][endTime]\": \"${railPoint.endTime}\",")
}
return "{ $sb }"
}
It is very dirty approach, but might be enough, as long as you don't make RailPoint
more complex, especially, if you don't add members that are custom classes or collections.
(I assumed that times are String
s, but if they are not, just add some date formatting in the formula)
Related Topics
Does Glide Have a Method for Loading Both Png and Svg
How to Delete a File on Google Drive Using Google Drive Android API
How to Skip Initial Data and Trigger Only New Updates in Firestore Firebase
How to Set Up Intellij Idea for Android Applications
How to Use Weakreference in Java and Android Development
How to Avoid Garbage Collection Delays in Java Games? (Best Practices)
How to Parse JSON from a Java Httpresponse
Android Web Scraping with a Headless Browser
How to Get Current Location in Googlemap Using Fusedlocationproviderclient
Android: Textview Automatically Truncate and Replace Last 3 Char of String
How to Hash a String in Android
Change Icons of Checked and Unchecked for Checkbox for Android
Android: How to Handle Button Click
How to Call a Restful Web Service from Android
How to Get Data from Each Dynamically Created Edittext in Android
Get a JSON Object from a Http Response