is there any simple example for Android of using JSON in a serialization?
Thanks
We use the gson library for that. Serialization is as simple as calling
new Gson().toJson(obj)
And for deserialization,
new Gson().fromJson(jsonStr, MyClass.class);
If you want to avoid using another library in your Android project just to (de)serialize JSON, you cau use following code as I do.
To serialize
JSONObject json = new JSONObject();
json.put("key", "value");
// ...
// "serialize"
Bundle bundle = new Bundle();
bundle.putString("json", json.toString());
and to deserialize
Bundle bundle = getBundleFromIntentOrWhaterver();
JSONObject json = null;
try {
json = new JSONObject(bundle.getString("json"));
String key = json.getString("key");
} catch (JSONException e) {
e.printStackTrace();
}
There is a simple library to (de)serialize JSON,compatible with android own json library.
// deserialize a java bean to json object
JSONObject studentJson = JsonDeer.toJson(student);
// serialize a java bean from json object
Student student1 = JsonDeer.fromJson(studentJson,Student.class);
library address
protected void onPostExecute(String results) {
if (results!=null) {
try {
Tec tec_m=new Tec();
tec_m=new Gson().fromJson(results, Technician.class);
((AndroidActivity)activity).setData(tec_m);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I need to show response on Sign Up, below is my JSON Response.
I should show password is too short(minimum is 5 characters) into one string
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
And also I need to parse the response from the following JSON data
as Signature has already been taken
{ errors: { signature: [ "has already been taken" ] } }
Please tell me how to parse the particular data from the JSON data.
Thanks in advance!!!!
You can use below method to parse your data.
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
You can replace unwanted symbols like below code:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
You can use Google's Gson library to do that using the following steps:
Add dependency in your build.gradle(Module:app) file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
For latest version of gson library, click here
To parse JSON string to an object use the code below:
Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
And if you need to convert an object to a JSON string, you can use the below code:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
Make sure you design your object appropriate for the JSON string to match the data types. If you are not sure of the data types in the JSON, you can use this site or any parse and view website to view them.
Hope it helps!
Just try this,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
It is possible to retrieve a JSON object without a key name?
One more problem is that it is deep in the hierarchy. Please see this: http://jsonviewer.stack.hu/#http://gateway.marvel.com/v1/public/characters?apikey=2d0af97a020cd072d49059aa0bf13207&hash=ef7184ddbb03ed2f71da0efec112cf41&ts=1495035369
That is an intensively long JSON and has multiple objects.
I am trying to access this part of the JSON: {
"id": 1010699,
"name": "Aaron Stack", ..
I am using the following code:
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("data");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("results");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I can't access it.
You can use GSON for this
compile 'com.google.code.gson:gson:2.7'
and create POJO class for the corroesponding json result using this link, Just paste your json data and create classes.
For eg your main pojo class name be JsonResponseHolder
And in your java code
try {
JsonResponseHolder jrh = new Gson().fromJson(responseString,
JsonResponseHolder.class);
List<Results> results = jrh.getData().getResults();
/// this will give the result objects
/// and be sure to convert [] arrays to list for better data handling
} catch (JSONException e) {
e.printStackTrace();
}
Hope this will help
I want to send this serialize Json in Soap web service parameter to get data from server. I don know how to serialize Json like below.
I am doing this -
JSONObject jsonObject = new JSONObject();
try {
JSONObject obj = new JSONObject();
//obj.put("MeterSrNo", txtMeterSrMo.getText().toString());
obj.put("MeterSrNo", txtMeterSrMo.getText().toString());
jsonObject.put("obj", obj);
jsonObject.put("SPName", "XXMFU_GETMobilityDetail");
} catch (JSONException e) {
e.printStackTrace();
}
And its giving me below output-
{'obj':{"MeterSrNo":"5"},'SPName':'XXMFU_GETMobilityDetail'}
But i want below output. How can i achieve this?
"{'\obj\':{\"MeterSrNo\":\"5\"},'\SPName\':'XXMFU_GETMobilityDetail'}"
By using Gson Library you can do serialization and desertification.
Serialization
new Gson().toJson(object)
Deserialization
new Gson().fromJson(jsonString, MyClass.class);
Try following way,
JSONObject jsonObject = new JSONObject();
JSONObject jsonMeterObject = new JSONObject();
try {
jsonMeterObject.put("MeterSrNo","5");
jsonObject.put("obj",jsonMeterObject);
jsonObject.put("SPName","XXMFU_GETMobilityDetail");
} catch (JSONException e) {
e.printStackTrace();
}
Output
{
"obj":{
"MeterSrNo":"5"
},
"SPName":"XXMFU_GETMobilityDetail"
}
I have the following json structure which i need to send it to server using post request. Please help in making the same structure by code in android.
The json structure is as follows :
{
"
}
}
Since i am newbie to android so please help.
Use the JSONObject class in android, here is an example:
JSONObject object = new JSONObject();
JSONObject cardAcceptorkey = new JSONObject();
try {
//CREATE cardAcceptorkey object
cardAcceptorkey.put("id","CA-IDCode");
cardAcceptorkey.put("name","USA");
...
//CREATE object
object.put("AuditNumber", "451035adss");
object.put("cardAcceptorkey", cardAcceptorkey);
...
} catch (JSONException e) {
e.printStackTrace();
}
More info: http://www.vogella.com/tutorials/AndroidJSON/article.html
{
"status": "ERROR",
"msg_content": "Your old password was entered incorrectly. Please enter it again.",
"code": "400",
"msg_title": "Sorry. Error in processing your request"
}
if (str.startsWith("Bad Request"))
{
textview.setText(" ");
}
How to print inside the textview to display the msg_content using json
You need to parse json using JSON object.
JSONObject obj = new JSONObject(str);
Then find string from JSON object whatever you want.
if (obj.has("msg_content")) {
String value = obj.getString("msg_content");
textview.settext(value);
}
You will need to create a JSONObject and pass it the string as a parameter.
JSONObject obj = new JSONObject(str);
Then to find a key in the JSONObject just call, always check if the JSONObject has that key before trying to retrieve it.
if (obj.has("status"){
String status = obj.getString("status");
}
if (obj.has("msg_content"){
String content = obj.getString("msg_content");
textview.setText(content);
}
JsonReader is implemented in API 11. If you want to use it in GingerBread or below try this
Use following Code for extracting Information from JSON Objects:
try {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(key.equals("msg_content"))
textView.setText(jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if u have JSON as String, u can populate an object using following code:
try {
jsonObject = new JSONObject(theJsonString);
} catch (JSONException e1) {
e1.printStackTrace();
}
I'm quite new to JSON but I would create a JsonReader and parse the JSON as per here