How to set and get json from setter/getter class? - java

this is my pojo class and i want make method add diary in my diary services class then how to get and set json in this method and any other way to get and set json from setter/getter class.
public class Dairy extends BaseEntity {
public String dairyId;
public String dairyType;
public String productName;
private List<Dairy> dataList;
public List<Dairy> getDataList() {
return dataList;
}
public void setDataList(List<Dairy> dataList) {
this.dataList = dataList;
}
public String getDairyId() {
return dairyId;
}
public void setDairyId(String dairyId) {
this.dairyId = dairyId;
}
public String getDairyType() {
return dairyType;
}
public void setDairyType(String dairyType) {
this.dairyType = dairyType;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}

If you hava json like this
product:{
dairyId:"1",
dairyType:"a",
productName:"New Year 2015"
}
You should get like
Dairy d=new Dairy();
You have to use jsonParser class.Then set value on object d.like
JSONObject jsonObject=getJSONObject("product");
d.setDairyId(jsonObject.getString("dairyId");
d.setDairyType(jsonObject.getString("dairyType");
d.setProductName(jsonObject.getString("productName");
To print this value you may use like:
System.out.println("Name is:"+d.getProductName());
I hope this will help to you :)

Related

com.google.gson.stream.MalformedJsonException error: How to solve it?

I want to get the country details from an external api and using Gson to set the data received from the get request to class Country. The problem is that in the response, the currencies key has value which is between [](please see below) and in some cases there is a space between the currencies name values which causes the following error
com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 41 path $.currencies[0].name:
"currencies":[{"code":"BGN","name":"Bulgarian lev","symbol":"лв"}]
#RestController
public class CountryController {
#Autowired
private RestTemplate restTemplate;
private static String baseURL = "https://restcountries.com/v2/";
public Object[] getCountryDetails(String countryName){
Object[] countryDetails = restTemplate.getForObject(baseURL+"name/"+countryName+"?fields=name,alpha2Code,alpha3Code,capital,currencies", Object[].class);
return countryDetails;
}
public Country createCountryObject(String countryName) {
String response = Arrays.asList(getCountryDetails(countryName)).get(0).toString();
Gson g = new Gson();
JsonReader reader = new JsonReader(new StringReader(response.trim()));
reader.setLenient(true);
Country country = g.fromJson(reader, Country.class);
return country;
}
#GetMapping("/")
public String getAll(){
Country country = createCountryObject("bulgaria");
return country.getName();
}
}
Country.java:
package country.neighbours.tour.models;
import java.util.List;
public class Country {
private String name;
private String alpha2Code;
private String alpha3Code;
private List<String> borders;
private Object[] currencies;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getBorders() {
return borders;
}
public void setBorders(List<String> borders) {
this.borders = borders;
}
public String getAlpha2Code() {
return alpha2Code;
}
public void setAlpha2Code(String alpha2Code) {
this.alpha2Code = alpha2Code;
}
public String getAlpha3Code() {
return alpha3Code;
}
public void setAlpha3Code(String alpha3Code) {
this.alpha3Code = alpha3Code;
}
public Object[] getCurrencies() {
return currencies;
}
public void setCurrencies(Object[] currencies) {
this.currencies = currencies;
}
}
How can I get only the currency code?
It looks like you are parsing the response twice; once with restTemplate.getForObject, then you convert its result to a String (the result of your toString() call is most likely not JSON) and then you try to parse it a second time with Gson.
In case you only want to use Gson, you can use a TypeToken in the fromJson call to parse the response JSON array:
List<Country> countries = gson.fromJson(..., new TypeToken<List<Country>>() {}.getType());
Maybe someone more familiar with Spring can also explain how to use only RestTemplate.getForObject for this instead of Gson.

Converting JSON to POJOs Using Java and assign values

I have some JSON objects and I need to changed them as JAVA classes and assign the given value.
{
"Summary":{
"AccountSummary":{
"Account_number": "324d",
"Account_name": "John"
},
"Transaction":[
{
"Date": "2021-08-21",
"Amount": "20,000"
},
{
"Date": "2021-08-23",
"Amount": "5,000"
}
]
}
}
These are the current coding I did,
//The account summary class with assigned value
public class AccountSummary{
#JsonProperty("Account_number")
public String account_number = "324d";
#JsonProperty("Account_name")
public String account_name = "John";
}
//Transaction class. I want to know how I can assign values
public class Transaction{
#JsonProperty("Date")
public String date;
#JsonProperty("Amount")
public String amount;
}
// Summary class
public class Summary{
#JsonProperty("AccountSummary")
public AccountSummary accountSummary;
#JsonProperty("Transaction")
public List<Transaction> transaction;
}
As I have assigned values for AccountSummary, I need to assign values for Transaction class also. But As if its a list I don't know how to assign. Please help.
You can do something like this,
First, create a maven project which has the below dependencies,
1. jackson-core
2. jackson-databind
3. jackson-annotations
make sure to have all three dependencies in the same version.
Then create separate model classes for your POJO objects
public class AccountSummary{
#JsonProperty("Account_number")
public String account_number;
#JsonProperty("Account_name")
public String account_name;
}
public class Transaction{
#JsonProperty("Date")
public String date;
#JsonProperty("Amount")
public String amount;
}
public class Summary{
#JsonProperty("AccountSummary")
public AccountSummary accountSummary;
#JsonProperty("Transaction")
public List<Transaction> transaction;
}
public class Root{
#JsonProperty("Summary")
public Summary summary;
}
Then create a Main.java class and implement the below code.
public class Main {
public static void main(String[] args) {
try {
ObjectMapper om = new ObjectMapper();
Root root = om.readValue(new File("your.value.json"),Root.class);
System.out.println(root);
} catch (Exception e) {
e.printStackTrace();
}
}
}
now when you execute you can see all the values in the json file are assigned correctly to your models.
So like this, you can map your json values to your objects.
You can try following for setting the value manually
Summary.java
public class Summary {
public AccountSummary accountSummary;
public List<Transaction> transaction;
public AccountSummary getAccountSummary() {
return accountSummary;
}
public void setAccountSummary(AccountSummary accountSummary) {
this.accountSummary = accountSummary;
}
public List<Transaction> getTransaction() {
return transaction;
}
public void setTransaction(List<Transaction> transaction) {
this.transaction = transaction;
}
}
Transaction.java
public class Transaction {
public String date;
public String amount;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
AccountSummary .java
public class AccountSummary {
public String account_number;
public String account_name;
public String getAccount_number() {
return account_number;
}
public void setAccount_number(String account_number) {
this.account_number = account_number;
}
public String getAccount_name() {
return account_name;
}
public void setAccount_name(String account_name) {
this.account_name = account_name;
}
}
final Code:-
AccountSummary a = new AccountSummary();
a.setAccount_name("xyz");
a.setAccount_number("xyz");
List<Transaction> transactionList = new ArrayList<Transaction>();
Transaction t = new Transaction();
t.setAmount("xyz");
t.setDate("xyx");
transactionList.add(t); // set the multiple object
// here is the final result
Summary s = new Summary();
s.setAccountSummary(a);
s.setTransaction(transactionList);

Jersey object's fromString method is not called

This is a follow up question to this question:
Passing custom type query parameter
I got a class which includes this method:
public static MyClass fromString(String json)
{
Gson gson = new Gson();
MyClass user = gson.fromJson(json, MyClass.class);
return user;
}
The full class:
public class MyClass
{
public String name;
public PortalNameEnum portalName;
public PortalUserTypeEnum portalUserType;
public String notes;
public MyClass(String name, PortalNameEnum portalName,
PortalUserTypeEnum portalUserType, String notes)
{
super();
this.portalName = portalName;
this.portalUserType = portalUserType;
this.name = name;
this.notes = notes;
}
public static MyClass fromString(String json)
{
Gson gson = new Gson();
PortalUserInfo user = gson.fromJson(json, PortalUserInfo.class);
return user;
}
public PortalNameEnum getPortalName()
{
return portalName;
}
public void setPortalName(PortalNameEnum portalName)
{
this.portalName = portalName;
}
public PortalUserTypeEnum getPortalUserType()
{
return portalUserType;
}
public void setPortalUserType(PortalUserTypeEnum portalUserType)
{
this.portalUserType = portalUserType;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getNotes()
{
return notes;
}
public void setNotes(String notes)
{
this.notes = notes;
}
}
I got a resource which got a method:
#Path("/myclasscall")
#GET
#UnitOfWork
public String registerPortalUser(#Context HttpServletRequest req, #QueryParam("callback") String callback, #QueryParam("myclass") MyClass recordData) throws Throwable
{ .. }
It seems like the fromString method is not called and the resource method is always null, even though I see in the console the request itself and I do see a string that has been passed. Why is that?
The problem was with the client.
Instead of passing a single parameter called "myclass", he passed all the fields separately. After merging them together into a single Json instance, it was fixed.

Assign one json value for two fields in java using GSON

I am trying to assign the value returned by some function to a field in the deserialized class of json.
FileInfo.java
public class FileInfo {
#SerializedName("Name")
private String mName;
#SerializedName("Url")
private String mUri;
#SerializedName("Size")
private Integer mSize;
#SerializedName("ModTime")
private Long mModifiedTime;
private FileType mType;
#SerializedName("Children")
private ArrayList<FileInfo> mChildren = new ArrayList<>();
public ArrayList<FileInfo> getChildren() {
return mChildren;
}
public long getModifiedTime() {
return mModifiedTime;
}
public String getName() {
return mName;
}
public Integer getSize() {
return mSize;
}
public String getUrl() {
return mUri;
}
public FileType getType() {
return mType;
}
public void setChildren(ArrayList<FileInfo> mChildren) {
this.mChildren = mChildren;
}
public void setModifiedTime(long mModifiedTime) {
this.mModifiedTime = mModifiedTime;
}
public void setName(String mName) {
this.mName = mName;
}
public void setSize(Integer mSize) {
this.mSize = mSize;
}
public void setType(FileType mType) {
this.mType = mType;
}
public void setUri(String mUri) {
this.mUri = mUri;
}
#Override
public String toString() {
return FileInfo.class.toString();
}
public FileInfo() {
}
}
The mType needs to be assigned to foo(mName). I looked up custom deserializers and instance creators but none of those helped. I also thought of TypeAdapters which i feel defeats the purpose of keeping deserialization(using GSON) simple.
This is a sample JSON string that will be deserialized.
[
{
"Name":"Airport",
"Url":"http://192.168.2.2/api/sites/Baltimore%20Airport/Airport",
"Size":0,
"ModTime":"2015-12-02T14:19:17.29824-05:00",
"Children":null
}
]
P.S. I'm not sure if this should be done during deserialization but trying anyways. Also please let me know of alternative ways to achieve this.

Using Jackson to parse Json map value into String or CustomClass

I'm being given a Json file with the form:
{
"descriptions": {
"desc1": "someString",
"desc2": {"name":"someName", "val": 7.0}
}
}
I have the POJO:
public class CustomClass {
Map<String, Object> descriptions;
public static class NameVal{
String name;
double val;
public NameVal(String name, double val){...}
}
}
I can recreate the json file with the code:
CustomClass a = new CustomClass();
a.descriptions = new HashMap<String, Object>();
a.descriptions.put("desc1", "someString");
a.descriptions.put("desc2", new CustomClass.NameVal("someName", 7.0));
new ObjectMapper().writeValue(new File("testfile"), a);
But, when I read the object back in using:
CustomClass fromFile = new ObjectMapper().readValue(new File("testfile"), CustomClass.class);
then fromFile.descriptions.get("desc2") is of type LinkedHashMap instead of type CustomClass.NameVal.
How can I get Jackson to properly parse the type of the CustomClass.NameVal descriptors (other than making some class that wraps the parsing and explicitly converts the LinkedHashMap after Jackson reads the file)?
Try this. Create a class Description with name and value attributes:
public class Description {
private String name;
private double val;
}
Now in your CustomClass do this:
public class CustomClass {
List<Description> descriptions;
}
And that's it. Remember to create getters and setters because Jackson needs it.
You could try something like this:
public class DescriptionWrapper {
private Description descriptions;
public Description getDescriptions() {
return descriptions;
}
public void setDescriptions(Description descriptions) {
this.descriptions = descriptions;
}
}
public class Description {
private String desc1;
private NameValue desc2;
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
public NameValue getDesc2() {
return desc2;
}
public void setDesc2(NameValue desc2) {
this.desc2 = desc2;
}
}
public class NameValue {
private String name;
private double val;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getVal() {
return val;
}
public void setVal(double val) {
this.val = val;
}
}

Categories