What steps will reproduce the problem?
1.I have a json reponse as
String Content =
"{
"region":{
"state.code":"TX",
"country-code":"USA"
}
}";
2.I want to convert this Json Object into Java Object.I have this Java class to convert
public class Region{
private String stateCode;
private String countryCode;
public String getStateCode ()
{
return stateCode;
}
public void setStateCode (String stateCode)
{
this.stateCode = stateCode;
}
public String getCountryCode ()
{
return countryCode;
}
public void setCountryCode (String countryCode)
{
this.countryCode = countryCode;
}
}
3.My problem is Java doesnt allow . or - in variable name.Which doesnt allow json string to map to Region java class object giving null .
gson.fromJson(Content, Region.class);
What is the expected output? What do you see instead?
Can anybody please help me in this?
I have tried #SerializedName annotations but it is not working.
What version of the product are you using? On what operating system?
Please provide any additional information below.
You're trying to map this JSON
{
"region":{
"state.code":"TX",
"country-code":"USA"
}
}
to an instance of type Region. That JSON is a JSON Object which contains a pair with name region and a value which is a JSON Object. That JSON Object has two pairs, one with name state.code and JSON String value TX and one with name country-code and JSON String value USA.
You can't map that to a Region object. You have to bypass the root's pair named region.
Create a encapsulating type
class RegionContainer {
private Region region;
// the rest
}
and map that
gson.fromJson(Content, RegionContainer.class);
#SerializedName will work for your fields.
#SerializedName("state.code")
private String stateCode;
Related
I am using JackSon to parse the following JSON:
{
"AwardID": "1111111",
"AwardTitle": "Test Title",
"Effort":
"[
{
"PersonFirstName": "Jon",
"PersonLastName": "Snow"
}
]"
}
I would like to flatten this to be used in the following class:
public class Award {
private String awardId;
private String awardTitle;
private String personFirstName;
private String personLastName;
}
I have tried the following and have gotten the first two values, but I haven't been able to get the values from Effort trying to use JsonUnwrapped. I noted that it doesn't work with arrays, but I am trying the objectMapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, true) configuration in the main method used to get the values.
public class Award {
#JsonProperty("AwardID")
private String awardId;
#JsonProperty("AwardTitle")
private String awardTitle;
#JsonUnwrapped
private Effort effort;
}
public class Effort {
private String personFirstName;
private String personLastName;
}
Note that I only expect one value in the Effort array from the API response at this time.
What is recommended to try next? Thank you!
The easiest way is having a List<Effort> if you have a JSON Array.
If there is always 1 item for Effort, the returning JSON should not have Effort as a JSON Array and instead should be a JSON Object.
But if you can only handle it codewise, you can have something like this (Note that there should always contain one item in Effort, otherwise it will throw Exception):
public class Award {
#JsonProperty("AwardID")
private String awardId;
#JsonProperty("AwardTitle")
private String awardTitle;
#JsonProperty("Effort")
private Effort effort;
}
public class Effort {
#JsonProperty("PersonFirstName")
private String personFirstName;
#JsonProperty("PersonLastName")
private String personLastName;
}
And your ObjectMapper needs to be enabled with DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS as well:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
Award award = mapper.readValue(rawJson, Award.class); // rawJson is your JSON String
And it should have the following output:
Award(awardId=1111111, awardTitle=Test Title, effort=Effort(personFirstName=Jon, personLastName=Snow))
Note that the annotation #JsonUnwrapped can only apply on JSON Object, not JSON Array:
Value is serialized as JSON Object (can not unwrap JSON arrays using this mechanism)
{
"users":[
{
"customerId":"2kXE3upOg5hnOG",
"ccoId":"paalle",
"userGroups":[
"CX Cloud Super Admins",
"CX Cloud Admins",
"aAutoGroupMarked12"
],
"emailId":"paalle#test.com",
"fullName":"Pavan Alle",
"isSelected":true
},
{
"customerId":"2kXE3upOg5hnOG",
"ccoId":"rtejanak",
"userGroups":[
"aTestUserGroupname1234"
],
"emailId":"rtejanak#test.com",
"fullName":"Raja Ravi Teja Nakirikanti"
}
],
"pagination":{
"pageNumber":1,
"totalPages":2,
"rowPerPage":10,
"totalRows":11
}
}
This is my JSON, where is want to extract ccoId, if and only if the userGroups have a group name as aAutoGroupMarked12. I am new to API automation and JsonPath.
In my company, we were told to use io.rest-assured API's JsonPath class. can someone please give me suggestions on how should I write a path which returns me ccoId value
I would use POJO to filter out the reults based on userGroups field.
POJO is a Java class representing JSON. Your JSON can be transformed into:
public class UserEntity {
public String customerId;
public String ccoId;
public List<String> userGroups;
public String emailId;
public String fullName;
public Boolean isSelected;
}
Each of the variable names need to be exactly like the names in the JSON.
Now, below line transforms JSON into List<UserEntity> so we transform JSON to Java classes
JsonPath jsonPath = JsonPath.from("json String or File");
UserEntity[] userEntities = jsonPath.getObject("$.users", UserEntity[].class);
We tell Rest-Assured's Json Path to look for users element in JSON. It's a list so we transform it into an Array, then we can also change it to list and iterate.
List<UserEntity> usersList = List.of(userEntities);
It will make it much easier to operate on. I would recommend using Streams but we'll use regular foreach in this case:
public void String getCcoId(List<UserEntity> usersList) {
for (UserEntity user : usersList) {
List<String> userGroups = user.userGroups;
for (String userGroup : userGroups) {
if (userGroup.equals("aAutoGroupMarked12")) {
return user.ccoId;
}
}
}
}
The code above looks for particular userGroup and if it matches first occurrence it returns ccoId
I am trying to deserialize a json string to POJO and then serialize it back to json string using Jackson, but in this process I want resultant json string to have changed key values.
e.g. input json string:
{"some_key":"value"}
here is what my POJO looks like
public class Sample {
#JsonProperty("some_key")
private String someKey;
public String getSomeKey(){
return someKey ;
};
}
When I serialize it again I want json string to be something like this
{"someKey":"value"} .
Is there any way I can achieve this?
I was able to do deserialization by renaming setter functions according to what is the input json string .
class Test{
private String someKey;
// for deserializing from field "some_key"
public void setSome_key( String someKey) {
this.someKey = someKey;
}
public String getSomeKey(){
return someKey;
}
}
You should be able to pull this off by defining a creator for deserialization and then let Jackson do its default behavior for serialization.
public class Sample {
private final String someKey;
#JsonCreator
public Sample(#JsonProperty("some_key") String someKey) {
this.someKey = someKey;
}
// Should serialize as "someKey" by default
public String getSomeKey(){
return someKey;
}
}
You may need to disable MapperFeature.AUTO_DETECT_CREATORS on your ObjectMapper for this to work.
I am trying find a Java lib/api that will allow me to turn the contents of a HTTP Request POST body into a JSON object.
Ideally I would like to use a Apache Sling library (as they are exposed in my container naturally).
The closest I've found it: org.apache.sling.commons.json.http which converts the header to JSON.
HTTP Post bodies are in the format; key1=value1&key2=value2&..&keyn=valueN so I assume there is something out there, but I havent been able to find it.
I may just have to use a custom JSONTokener (org.apache.sling.commons.json.JSONTokener) to do this if something doesn't already exist. Thoughts?
Thanks
Assuming you're using an HttpServlet and a JSON library like json-simple you could do something like this:
public JSONObject requestParamsToJSON(ServletRequest req) {
JSONObject jsonObj = new JSONObject();
Map<String,String[]> params = req.getParameterMap();
for (Map.Entry<String,String[]> entry : params.entrySet()) {
String v[] = entry.getValue();
Object o = (v.length == 1) ? v[0] : v;
jsonObj.put(entry.getKey(), o);
}
return jsonObj;
}
With example usage:
public void doPost(HttpServletRequest req, HttpServletResponse res) {
JSONObject jsonObj = requestParamsToJSON(req);
// Now "jsonObj" is populated with the request parameters.
// e.g. {"key1":"value1", "key2":["value2a", "value2b"], ...}
}
Jackson is also a good option - its used extensively in Spring. Here is the tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
I recommend trying Apache Commons Beanutils.
ServeltRequest request;
Map map = request.getParameterMap();
MyObject object = new MyObject();
BeanUtils.populate(object, map);
String json = object.toJSON() //using any JSON library
Sorry on making this an own answer but obviously my reputation doesn't allow me to simply add a comment to the answer How to convert HTTP Request Body into JSON Object in Java of maerics.
I would also iterate over the request params but instead of using an arbitrary json library use the JSONObject that is provided by sling. http://sling.apache.org/apidocs/sling6/org/apache/sling/commons/json/JSONObject.html
import org.json.JSONObject;
JSONObject json = new JSONObject(request.getParameterMap())
Use Gson. With this you can create class with private variables which represent the data you want : for example.
meta:{
name:"Example"
firstname:"Example2"
}
data:[
{
title:"ecaetra"
description:"qwerty"
}
...
]
Json Object could be retrieve like this :
public class RetrieveData {
private Meta meta;
private List<Data> data;
public Meta getMeta(){
return meta;
}
public List<Data> getData(){
return data;
}
}
public class Meta {
private String name;
private String firstname;
public String getName(){
return name;
}
public String getFirstName(){
return firstname;
}
}
public class Data {
private String title;
private String description;
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
}
And your instruction are simple. Content is the content of your Page, you can retrieve it with Asynctask.
Object o = new Gson().fromJson(Content, RetrieveData.class);
data = (RetrieveData)o;
// Get Meta
data.getName(); // Example
data.getFirstName(); // Example2
// Get Data
data.get(0).getTitle(); // position 0 : ecaetra
data.get(0).getDescription(); // position 0 : qwerty
I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:
"Info":[
{
"Id":"",
"Name":"",
"Description":"",
"Date":""
}
In order to parse this I need to "dot" in. Ex: Info.Name
How can I do this in a serialized DTO?
#SerializedName("Name")
public String name;
#SerializedName("Description")
public String desc;
#SerializedName("Date")
public String date;
I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.
Can anyone help?
EDIT: I have tried everything you guys posted, and nothing works. The error says:
The JsonDeserializer failed to deserialize json object {"Info":[{".......
SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!
I am assuming that the actual JSON you are intaking is valid because the example you provided is not. In your JSON example, you have "Info":[ but there is no outer object containing the "Info" property, which is a must. The valid JSON would be:
{
"Info": [
{
"Id":"",
"Name":"",
"Description":"",
"Date":"",
}
]
}
This is a JSON object that has a property "Info" which has a value that is a list of objects. This list of objects contains one object that has the properties "Id", "Name", "Description", and "Date", all of which have empty-string values.
Here is a quick tutorial on how to use GSON to parse a JSON feed such as the above JSON:
You will need a class to represent the items in the list:
public class InfoItem {
public String Id;
public String Name;
public String Description;
public String Date;
public InfoItem() {}
}
And one to represent the list of Items:
public class InfoItemList extends LinkedList<InfoItem> {
public InfoItemList() { super() };
}
This added complexity is because GSON cannot otherwise get the type of a generic collection from the class data.
And one to represent the overall JSON message:
public class InfoMessage {
public InfoItemList Info;
public InfoMessage() {};
}
And then just:
gson.fromJson(jsonString, InfoMessage.getClass());
If just de-serializing a collection:
Type listType = new TypeToken<List<InfoItem>>() {}.getType();
gson.fromJson(jsonString2, listType);
The Info object is a list because of the []. You have to use the following code to deserialze it:
EDIT:
public class Info {
// as in your question
public String name;
...
}
public class Data {
#SerializedName("Info")
public List<Info> info;
}
Then just use the data class to deserialize your json.