SoapObject data=(SoapObject) envelope.bodyIn;
String result = String.valueOf(((SoapObject) envelope.bodyIn).getProperty(0));
JSONObject _jobjec = new JSONObject(result);
UserId = _jobjec.get("UserId").toString();
UserParentId = _jobjec.get("UserParentId").toString();
UserName = _jobjec.get("UserName").toString();
UserPassword = _jobjec.get("UserPassword").toString();
UserMobile = _jobjec.get("UserMobile").toString();
UserEmail = _jobjec.get("UserEmail").toString();
UserMpin = _jobjec.get("UserMpin").toString();
This is my COde i am trying to JOSon Parse and get value but what happen { ,} remove in result when i make json Object and trying and get value then i get Excepion i am getting
String.valueOf(((SoapObject) envelope.bodyIn).getProperty(0) :
{"UserId":"2","UserParentId":"1","UserName":"Anilkumar","UserPassword":"12546",
"UserMobile":"8130513899","UserEmail":"anilaat87#gmail.com","UserMpin":"7890",
"UserBalance":"20.0000","UserResponseMessage":"Is Valid"}
but unable to parse it
Directly using JSONObject to parse POJO is tedious and error prone, recommended using one of the below libraries:
GSON
JACKSON
MOSHI
JSON.simple
First, define your POJO class, you can use some online service, e.g. this one or this,
Just paste your example json string, then you can get below pojo class (you don't need to write it on your own) in 2 seconds:
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("UserId")
#Expose
public String userId;
#SerializedName("UserParentId")
#Expose
public String userParentId;
#SerializedName("UserName")
#Expose
public String userName;
#SerializedName("UserPassword")
#Expose
public String userPassword;
#SerializedName("UserMobile")
#Expose
public String userMobile;
#SerializedName("UserEmail")
#Expose
public String userEmail;
#SerializedName("UserMpin")
#Expose
public String userMpin;
#SerializedName("UserBalance")
#Expose
public String userBalance;
#SerializedName("UserResponseMessage")
#Expose
public String userResponseMessage;
}
Then to get the java object, use below gson calls:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Example instance = gson.fromJson(jsonString, Example.class);
If you use Jackson or other libraries, the same process applies, and they differ only in the detailed function calls.
you have to write code like this
SoapObject data=(SoapObject) envelope.bodyIn;
String result = String.valueOf(((SoapObject)envelope.bodyIn).getProperty(0));
JSONObject _jobjec = new JSONObject(result);
UserId = _jobjec.getString("UserId");
UserParentId = _jobjec.getString("UserParentId");
UserName = _jobjec.getString("UserName");
UserPassword = _jobjec.getString("UserPassword");
UserMobile = _jobjec.getString("UserMobile");
UserEmail = _jobjec.getString("UserEmail");
UserMpin = _jobjec.getString("UserMpin");
Related
I am facing with a IMHO a strange behaviour of GSON. Let's take the following example:
{
"Name": "emaborsa",
"Surname": null
}
and my POJO is:
public class User {
#SerializedName("Name")
private String name;
#SerializedName("Surname")
private String surname;
// getter and setter
}
I deserialize it using the following code:
Gson g = new Gson();
User user = g.fromJson(json, User.class);
The variable name is set with "emaborsa", the variable surname I expected it were set to null but there is a string "null " instead.
Is it the correct behaviour or am I missing something? I tried to google it but it is hard to find something related to String and null...
This worked fine for me, using your code as the basis:
package gsonexample3;
import com.google.gson.Gson;
import com.google.gson.annotations.*;
public class User {
public static void main(String[] args) {
Gson g = new Gson();
User user = g.fromJson(json, User.class);
}
#SerializedName("Name")
private String name;
#SerializedName("Surname")
private String surname;
private static String json = "{\"Name\": \"emaborsa\", \"Surname\": null}";
}
Looks like you have to specify that you want to serialize nulls.
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
Coming from - https://howtodoinjava.com/gson/serialize-null-values/
I am using Jackson library with java 11 so basically I am able to read the below JSON into a string format
{
"schemas":[
"urn:params:core:2.0:User",
"urn:params:core:3.0:User"
],
},
}
here below is the set in which I have to fill the values of schemas from above json
private Set<String> setschemas = null;
right now I am able to read the above json into a string named finaljson , now please advise how can I read the differnt value of schemas from above json string named finaljson and set it to set named setschemas
if (node.has("schemas")) {
// *** here I want to read the differernt value of schemas and set it to a set
// named setschemas
// *****
}
you can create the following classes that represent the json structure
class MyJsonObject {
private AppIdentity appIdentity;
private Set<String> schemas;
private String userName;
}
class AppIdentity {
private String clientId;
private String username;
}
than you can use
final MyJsonObject myJsonObject = new ObjectMapper().readValue(finaljson, MyJsonObject.class); to read the json to JAVA object
so it can manipulated like myJsonObject.schemas.size() > 0 and such...
there are a lot of examples in the internet
*keep in mind, this solution only works when the json structure and fields name are known in advanced
With your approach, this would be simplest one:
if(node.has("schemas")) {
JsonNode schemaNode = node.get("schemas");
Set<String> schemaSet = objectMapper.convertValue(schemaNode, Set.class);
System.out.println("schemaSet" + schemaSet);
}
There are various ways to deal with JSON one is described here
1) You can create a class of JSON structure as follows with help online JSON to POJO convertor (Note:: Add Setters and Getters with help of IDE)
class AppJson {
private Set<AppIdentity> appIdentity;
private Set<String> schemas;
private String userName;
private Manager ManagerObject;
private String division;
private String organization;
private String costCenter;
private String employeeNumber;
}
class AppIdentity {
private String clientId;
private String username;
}
class Manager {
private String value;
private String $ref;
private String displayName;
private String $Ref;
}
2) Use above for object conversion.
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"appIdentity\":[{\"clientId\":\"9a41763c642\",\"username\":\"XXX\"}],\"schemas\":[\"urn:params:core:2.0:User\",\"urn:params:core:3.0:User\"],\"userName\":\"ajklmnop_699100\",\"manager\":{\"value\":\"string\",\"$ref\":\"sdkoirk\",\"displayName\":\"string\",\"$Ref\":\"sdkweoirk\"},\"division\":\"string\",\"organization\":\"string\",\"costCenter\":\"string\",\"employeeNumber\":\"string\"}\n"
+ "";
AppJson appJson = objectMapper.readValue(jsonString, AppJson.class);
System.out.println("json " + appJson.getSchemas());
Here you will get the schemas.
I have a POJO class like this. I am deserializing my JSON to below POJO first..
public class Segment implements Serializable {
#SerializedName("Segment_ID")
#Expose
private String segmentID;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("DateTime")
#Expose
private String dateTime;
private final static long serialVersionUID = -1607283459113364249L;
...
...
...
// constructors
// setters
// getters
// toString method
}
Now I am serializing my POJO to a JSON like this using Gson and it works fine:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(user.getSegments());
System.out.println(json);
I get my json printed like this which is good:
[{"Segment_ID":"543211","Status":"1","DateTime":"TueDec2618:47:09UTC2017"},{"Segment_ID":"9998877","Status":"1","DateTime":"TueDec2618:47:09UTC2017"},{"Segment_ID":"121332121","Status":"1","DateTime":"TueDec2618:47:09UTC2017"}]
Now is there any way I can convert "Segment_ID" to all lowercase while deserializing? I mean "Segment_ID" should be "segment_id" and "Status" should be "status". Is this possible to do using gson? So it should print like this instead.
[{"segment_id":"543211","status":"1","datetime":"TueDec2618:47:09UTC2017"},{"segment_id":"9998877","status":"1","datetime":"TueDec2618:47:09UTC2017"},{"segment_id":"121332121","status":"1","datetime":"TueDec2618:47:09UTC2017"}]
if I change the "SerializedName" then while deserializing my JSON to POJO, it doesn't work so not sure if there is any other way.
You need to provide alternative names for deserialisation process and primary (value property) for serialisation.
class Segment {
#SerializedName(value = "segment_id", alternate = {"Segment_ID"})
#Expose
private String segmentID;
#SerializedName(value = "status", alternate = {"Status"})
#Expose
private String status;
#SerializedName(value = "datetime", alternate = {"DateTime"})
#Expose
private String dateTime;
}
Now, you can deserialise fields: Segment_ID, DateTime, Status and still be able to serialise as desired.
I am using #JsonIgnore property to ignore some attributes in pojo, but these fields are not ignore in json response after parsing json using Gson library please help.
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class RideInvite extends RideInviteOld implements Serializable
{
private static final long serialVersionUID = -3729010679180341959L;
private double newFare = -1;
#JsonIgnore
private long prefPickupDropId;
#JsonIgnore
private String pickupLandmark;
#JsonIgnore
private String dropLandmark;
}
using following code to parse
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
jsonText = gson.toJson(msgObject);
Response after parsing
{"newFare":-1.0,"prefPickupDropId":2,"savePickupDropPoints":false,"pickupDropBasedOnTraffic":true,"allowFareChange":true}
here prefPickupDropId and savePickupDropPoints are json ignored but still value attribute is present in json text
I can not use #Expose for fields because my project is build in such away that ignoring fields which are not required json ignore and same pojos are using for preparing http response. This was working fine earlier but recently I am facing this issue
thanks in advance
Approach1:
Instead of using com.fasterxml.jackson.annotation.JsonIgnore you should use
com.google.gson.annotations.Expose to achieve your requirement.
Here is working code snippet -
import java.io.Serializable;
import com.google.gson.annotations.Expose;
public class RideRecord implements Serializable {
#Expose
private double newFare = -1;
private long prefPickupDropId;
private String pickupLandmark;
private String dropLandmark;
public RideRecord(double newFare, long prefPickupDropId, String pickupLandmark, String dropLandmark) {
super();
this.newFare = newFare;
this.prefPickupDropId = prefPickupDropId;
this.pickupLandmark = pickupLandmark;
this.dropLandmark = dropLandmark;
}
}
use the following code to parse:
RideRecord msgObject = new RideRecord(-1.0, 2, "sfo", "powell bart station");
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
String jsonText = gson.toJson(msgObject);
System.out.println(jsonText);
It will give output:
{"newFare":-1.0}
because only newFare is the field which is exposed.
you can play with the #Expose attribute to meet your requirements.
Approach2:
If you don't want to use #Expose then also you can achieve your
requirement by just creating Gson object as below -
RideRecord msgObject = new RideRecord(-1.0, 2, "sfo", "powell bart station");
GsonBuilder builder = new GsonBuilder();
builder.addSerializationExclusionStrategy(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
return fieldAttributes.getName().equals("prefPickupDropId") || fieldAttributes.getName().equals("pickupLandmark") || fieldAttributes.getName().equals("dropLandmark");
}
#Override
public boolean shouldSkipClass(Class<?> arg0) {
// TODO Auto-generated method stub
return false;
}
});
Gson gson = builder.create();
String jsonText = gson.toJson(msgObject);
System.out.println(jsonText);
In this case also you will get the same output :
{"newFare":-1.0}
You're using Jackson with GSON and those are too separate frameworks.
One of the approaches is to initialize Gson to exclude fields that do not have the expose annotation.
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Then mark every field you need to use with the #Expose annotation:
ex:
class MyClass {
#Expose public String name;
}
I'm having following class
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public Result OperationResult;
public String Messages;
public String UpdateAvailable;
public Object ResultData;
}
I'm having json string like,
{"OperationResult":0,"Messages":"","UpdateAvailable":"","ResultData":{"SessionId":"3b44a524-fc2a-499b-a16e-6d96339a6b5b","UserName":"admin","AccoundId":null,"Roles":["Administrator"],"DisplayName":"Admin","Status":3,"Type":1}}
I want to assign this json string to above class.I'm using GSON for assign json string to java object.In normal class i can assign json string to java object. But for this class i couldn't assign directly. Please any one help me,
Now i'm assigning like,
String formatedjsonstring = {json string};
Log.i("FORMAT STRING:",formatedjsonstring);
Gson gson = new Gson();
ReturnData returndata = (ReturnData) gson.fromJson(
formatedjsonstring, ReturnData.class);
You could use JavaJson from sourceforge. You could pass your json string to JsonObject .parse().
Try this
JsonObject json = JsonObject .parse("{\"OperationResult\":0, \"Messages\":\"UpdateAvailable\"");
System.out.println("OperationResult=" + json.get("OperationResult"));
System.out.println("Messages=" + json.get("Messages"));
https://sourceforge.net/projects/javajson/
Since your Java class doesn't resemble your JSON in any way, shape or form ... you're going to have a problem with that.
Problem #1: OperationResult should be an int
Problem #2: You're declared ResultData as an Object ... Java doesn't work like that.
You need your POJO to match the JSON:
public class ReturnData {
public ReturnData() {
OperationResult = Result.Failed;
Messages = "An Error Occured";
UpdateAvailable = "0";
ResultData = "";
}
public int OperationResult;
public String Messages;
public String UpdateAvailable;
public MyResultData ResultData;
}
class MyResultData {
public String SessionId;
public String UserName;
public String AccountId;
public List<String> Roles;
public String DisplayName;
public int Status;
public int Type;
}
ReturnData rd = new Gson().fromJson(jsonString, ReturnData.class);
I'd also consider using Gson's #SerializedName("name") annotation to convert the PascalCase field names in your JSON to camelCase field names in Java.
#SerializedName("OperationResult") public int operationResult;
Try this:
java.lang.reflect.Type type = new TypeToken<ReturnData>(){}.getType();
ReturnData rd = new Gson().fromJson(jsonString, type);