Deserialize JSON by property - java

I have a simple wrapper class.
class Wrapper {
int id;
Object command;
}
command could be an object that I get from the outside, and I cannot create an interface to hold the possible types together.
I'd like to serialize it simply:
String json = objectMapper.writeValueAsString(wrapper);
So that I get:
{"id":"1","command":{"type" : "objectType", "key0": "val0", ... other properties...}}
Ideally I'd build a registry with the possible values of type and the corresponding class names as values, so I could deserialize it like this:
Wrapper wrapper = objectMapper.readValue(bytes, Wrapper.class);
(objectMapper is com.fasterxml.jackson.databind.ObjectMapper)
Is there a way to achieve this with Jackson?

You can use the Jackson polymorphic type handling. You can declare which type the command property can be using #JsonTypeXXX annotations.
Here is a complete example:
public class JacksonTypeInfoOnObject {
public static class Bean {
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
#JsonSubTypes({
#JsonSubTypes.Type(Command1.class),
#JsonSubTypes.Type(Command2.class)
})
public final Object command;
#JsonCreator
public Bean(#JsonProperty("command") final Object command) {this.command = command;}
#Override
public String toString() {
return "Bean{" +
"command=" + command +
'}';
}
}
#JsonTypeName("cmd1")
public static class Command1 {
#Override
public String toString() {
return "Command1{}";
}
}
#JsonTypeName("cmd2")
public static class Command2 {
#Override
public String toString() {
return "Command2{}";
}
}
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
final List<Bean> list = Arrays.asList(
new Bean(new Command1()),
new Bean(new Command2()));
final String json = mapper.writeValueAsString(list);
System.out.println(json);
final List<Bean> values = mapper.readValue(json, new TypeReference<List<Bean>>() {});
System.out.println(values);
}
}
Output:
[{"command":{"type":"cmd1"}},{"command":{"type":"cmd2"}}]
[Bean{command=Command1{}}, Bean{command=Command2{}}]

I changed the type of your command property to a Map<String, Object> and the Wrapper object can be serialized/deserialized as expected.
Below, is the output generated by the Main class:
SERIALIZE: {"id":1,"command":{"key0":"val0","type":"objectType"}}
DESERIALIZE: Wrapper [id=1, command={key0=val0, type=objectType}]
Main.java
package json;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
static ObjectMapper objectMapper = new ObjectMapper();
private static Wrapper createWrapper() {
Wrapper wrapper = new Wrapper();
Map<String, Object> command = new HashMap<String, Object>();
command.put("type", "objectType");
command.put("key0", "val0");
wrapper.id = 1;
wrapper.command = command;
return wrapper;
}
private static String serializeWrapper(Wrapper wrapperObj) {
try {
return objectMapper.writeValueAsString(wrapperObj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
private static Wrapper deserializeWrapper(String wrapperJsonStr) {
try {
return objectMapper.readValue(wrapperJsonStr, Wrapper.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Wrapper wrapper = createWrapper();
String wrapperJsonStr = serializeWrapper(wrapper);
System.out.printf("SERIALIZE: %s%n", wrapperJsonStr);
Wrapper wrapperObj = deserializeWrapper(wrapperJsonStr);
System.out.printf("DESERIALIZE: %s%n", wrapperObj);
}
}
Wrapper.java
package json;
import java.util.Map;
public class Wrapper {
public int id;
public Map<String, Object> command;
#Override
public String toString() {
return "Wrapper [id=" + id + ", command=" + command + "]";
}
}

Related

How to sum values of jsonObject and create new jsonobject of sum inside a jsonArray in JAVA?

I have JSON Array as below and want to sum values of JSON object and create new JSON object of sum inside a JSON array:
{
"client":[
{
"member":12,
"group":"g1"
},
{
"member":17,
"group":"g2"
}
],
"client2":[
{
"member":14,
"group":"g11"
},
{
"member":175,
"group":"g22"
}
]
}
I want to sum the member value for each jsonobject inside the jsonarray and create extra json and put it inside client array. The expected json should look like below:
{
"client":[
{
"member":12,
"group":"g1"
},
{
"member":17,
"group":"g2"
},
{
"totalMember":29,
"group":"all"
}
],
"client2":[
{
"member":14,
"group":"g11"
},
{
"member":175,
"group":"g22"
},
{
"totalMember":189,
"group":"all"
}
]
}
I tried as:
mainJson.fieldNames().forEach(fn->{
JsonArray jsonArray = mainJson.getJsonArray(fn);
int id = 0;
for (int i = 0; i < jsonArray.size(); i++) {
id += jsonArray.getJsonObject(i).getInteger("id");
JsonObject jsonObject = new JsonObject().put("id",id).put("group","all");
jsonArray.add(jsonObject);
mainJson.put(fn,jsonArray);
}
});
Your expected JSON string is not normal because any JSON objects belong to the same JSON array should have the same structure, so the output JSON string should look like as below:
{
"client":[
{
"member":12,
"group":"g1"
},
{
"member":17,
"group":"g2"
},
{
"member":29,
"group":"all"
}
],
...
}
If your expected JSON string can be revised so, then here comes another way to achieve what you want by following steps with Jackson and Lambda Expression (since Java 8):
Step 1
Create POJOs and use #JsonAnySetter to serialize client and client2 to List<ClientInfo>, and use #JsonIgnore for getName() for deserialization to ignore field name.
class RootPojo {
private List<ClientInfo> clients = new ArrayList<>();
#JsonAnySetter
public void setClients(String name, List<ClientInfo> client) {
client.forEach(e -> {
e.setName(name);
});
this.clients.addAll(client);
}
//general getter and toString
}
class ClientInfo {
private String name;
private int member;
private String group;
#JsonIgnore
public String getName() {
return name;
}
//general getters, setters and toString
}
Step 2
Serialize JSON string to pre-defined POJOs with Jackson:
ObjectMapper mapper = new ObjectMapper();
RootPojo rootPojo = mapper.readValue(inputJsonStr, RootPojo.class);
System.out.println(rootPojo.toString());
Console output:
RootPojo [clients=[ClientInfo [name=client, member=12, group=g1], ClientInfo [name=client, member=17, group=g2], ClientInfo [name=client2, member=14, group=g11], ClientInfo [name=client2, member=175, group=g22]]]
Step 3
Use Lambda Expression for grouping and summation which will also add the results as new JSON objects back to original JSON string.
rootPojo.getClients()
.stream()
.collect(Collectors.groupingBy(ClientInfo::getName,
Collectors.summingInt(ClientInfo::getMember)))
.forEach((k,v) -> {
ClientInfo clientInfo = new ClientInfo();
clientInfo.setName(k);
clientInfo.setGroup("all");
clientInfo.setMember(v);
rootPojo.getClients().add(clientInfo);
});
System.out.println(rootPojo.toString());
Console output:
RootPojo [clients=[ClientInfo [name=client, member=12, group=g1], ClientInfo [name=client, member=17, group=g2], ClientInfo [name=client2, member=14, group=g11], ClientInfo [name=client2, member=175, group=g22], ClientInfo [name=client, member=29, group=all], ClientInfo [name=client2, member=189, group=all]]]
Step 4
Transform rootPojo into Map<String, List<ClientInfo> then deserialize it to output JSON string:
Map<String, List<ClientInfo>> clientMap = new HashMap<>();
rootPojo.getClients().forEach(e -> {
if (clientMap.containsKey(e.getName())) {
clientMap.get(e.getName()).add(e);
} else {
List<ClientInfo> clients = new ArrayList<>();
clients.add(e);
clientMap.put(e.getName(), clients);
}
});
String outputJsonStr = mapper.writeValueAsString(clientMap);
System.out.println(outputJsonStr);
Console output:
{"client":[{"member":12,"group":"g1"},{"member":17,"group":"g2"},{"member":29,"group":"all"}],"client2":[{"member":14,"group":"g11"},{"member":175,"group":"g22"},{"member":189,"group":"all"}]}
So, below is a full worked example using gson library (googles json parser).
First i created the class for defining the initial json file:
import java.io.Serializable;
import java.util.ArrayList;
public class ClientSer implements Serializable {
ArrayList<ClientDataSer> client;
ArrayList<ClientDataSer> client2;
public ClientSer(ArrayList<ClientDataSer> client, ArrayList<ClientDataSer> client2) {
this.client = client;
this.client2 = client2;
}
public ArrayList<ClientDataSer> getClient() {
return client;
}
public void setClient(ArrayList<ClientDataSer> client) {
this.client = client;
}
public ArrayList<ClientDataSer> getClient2() {
return client2;
}
public void setClient2(ArrayList<ClientDataSer> client2) {
this.client2 = client2;
}
}
With client data ser looking like:
public class ClientDataSer extends ClientDataParentSer {
int member;
public ClientDataSer(int member, String group) {
super(group);
this.member = member;
}
public int getMember() {
return member;
}
public void setMember(int member) {
this.member = member;
}
}
In order for gson to uses files as definitions of data structure, they need to be serialisable. I will get the why ClientDataSer extends ClientDataParentSer in a moment.
The code for reading this file, caluclating the total member value and printing it to another file is shown below:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
try (Reader reader = new FileReader("test.json")) {
// Convert JSON File to Java Object
ClientSer clientSer = gson.fromJson(reader, ClientSer.class);
ClientNewSer clientNewSer = new ClientNewSer(getNewClientData(clientSer.getClient()), getNewClientData(clientSer.getClient2()));
try {
Writer writer = new FileWriter("testNew.json");
gson.toJson(clientNewSer, writer);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static ArrayList<ClientDataParentSer> getNewClientData(ArrayList<ClientDataSer> clientDataSerList) {
ArrayList<ClientDataParentSer> clientDataSers = new ArrayList<>();
int memberCounter = 0;
for (ClientDataParentSer clientDataSer : clientDataSerList) {
clientDataSers.add(clientDataSer);
memberCounter += ((ClientDataSer)clientDataSer).getMember();
}
ClientDataNewSer clientDataNewSer = new ClientDataNewSer("all", memberCounter);
clientDataSers.add(clientDataNewSer);
return clientDataSers;
}
}
So, as you wanted client and client2 to contain a list each with 2 different obejects (one with field member and group, and the other with fields total member and group), we had to do some hierarchy stuff.
If we make a parent class containing the common field (group):
import java.io.Serializable;
public class ClientDataParentSer implements Serializable {
private final String group;
public ClientDataParentSer(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
}
and then make ClientDataSer and a new class:
public class ClientDataNewSer extends ClientDataParentSer {
int member;
public ClientDataNewSer(String group, int member) {
super(group);
this.member = member;
}
public int getMember() {
return member;
}
public void setMember(int member) {
this.member = member;
}
}
extend this parent class, we can have a list of ClientDataParentSer that contain both, ie the list the output json file needs.
the class for the new object is shown below:
import java.io.Serializable;
import java.util.ArrayList;
public class ClientNewSer implements Serializable {
ArrayList<ClientDataParentSer> client;
ArrayList<ClientDataParentSer> client2;
public ClientNewSer(ArrayList<ClientDataParentSer> client, ArrayList<ClientDataParentSer> client2) {
this.client = client;
this.client2 = client2;
}
public ArrayList<ClientDataParentSer> getClient() {
return client;
}
public void setClient(ArrayList<ClientDataParentSer> client) {
this.client = client;
}
public ArrayList<ClientDataParentSer> getClient2() {
return client2;
}
public void setClient2(ArrayList<ClientDataParentSer> client2) {
this.client2 = client2;
}
}
Any questions about anything comment below.
The full project is on my github here

How to process JSON Array nested inside an Array in java

Here is a java class CreateDoc which is sent from One web service that is producer side to another web service which is consumer side as List with content-type:Json
Below is the class representation
class CreateDoc{
DocMetData dMetaData;
DocContent dCont;
}
Class DocMetData {
String docNamel
String docType;
}
Class DocContent {
String data;
}
Once i receive the List as json in the consumer side i am not able to use this as a java Object and the content type is array with json nested inside an array.
Below is the Representation:
[
[
{
"dMetaData":{
"docName":"string",
"docType":"pdf"
},
"dCont":{
"data":"abc"
}
},
{
"dMetaData":{
"docName":"string",
"docType":"pdf"
},
"dCont":{
"data":"def"
}
},
{
"dMetaData":{
"docName":"string",
"docType":"pdf"
},
"dCont":{
"data":"ghk"
}
}
]
]
Question is how to process this and be able to use the data and represent as List.
Here's some sample code that shows how you can use the Jackson ObjectMapper to parse the data. Note that the code assumes the data is stored in a file, you can modify it as needed to suit your needs.
Here's the main class:
package parsing.arrayofarray;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ArrayOfArray {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String data = null;
try {
data = new String(Files.readAllBytes(Paths.get("src/main/resources/jsonArrayOfArray.json")));
} catch (IOException e1) {
e1.printStackTrace();
}
List<List<CreateDoc>> results = null;
try {
results = mapper.readValue(data, new TypeReference<List<List<CreateDoc>>>(){});
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(results);
}
}
and here are the supporting classes, first CreateDoc:
package parsing.arrayofarray;
public class CreateDoc {
DocMetData dMetaData;
DocContent dCont;
public DocMetData getdMetaData() {
return dMetaData;
}
public void setdMetaData(DocMetData dMetaData) {
this.dMetaData = dMetaData;
}
public DocContent getdCont() {
return dCont;
}
public void setdCont(DocContent dCont) {
this.dCont = dCont;
}
#Override
public String toString() {
return "CreateDoc [dMetaData=" + dMetaData + ", dCont=" + dCont + "]";
}
}
and DocContent:
package parsing.arrayofarray;
public class DocContent {
#Override
public String toString() {
return "DocContent [data=" + data + "]";
}
String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
and the DocMetData:
package parsing.arrayofarray;
public class DocMetData {
String docName;
String docType;
public String getDocNamel() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
#Override
public String toString() {
return "DocMetData [docNamel=" + docName + ", docType=" + docType + "]";
}
public String getDocType() {
return docType;
}
public void setDocType(String docType) {
this.docType = docType;
}
}
The output from the println is:
[[CreateDoc [dMetaData=DocMetData [docNamel=string, docType=pdf], dCont=DocContent [data=abc]], CreateDoc [dMetaData=DocMetData [docNamel=string, docType=pdf], dCont=DocContent [data=def]], CreateDoc [dMetaData=DocMetData [docNamel=string, docType=pdf], dCont=DocContent [data=ghk]]]]
You can use JSONArray(org.json) to parse the first list, and parse with GSON the inside list to create a List of CreatDoc. You can use only GSON to parse the first array too
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
public class Deserializer {
public static void main(String[] args) {
JSONArray jsonArray = new JSONArray(
"[[{\"dMetaData\": {\"docName\": \"string\",\"docType\": \"pdf\"},\"dCont\": {\"data\": \"abc\"}},{\"dMetaData\": {\"docName\": \"string\",\"docType\": \"pdf\"},\"dCont\": {\"data\": \"def\"}},{\"dMetaData\": {\"docName\": \"string\",\"docType\": \"pdf\"},\"dCont\": {\"data\": \"ghk\"}}]]");
JSONArray docsArray = jsonArray.getJSONArray(0);
List<CreateDoc> docsList = new Gson().fromJson(docsArray.toString(),
new TypeToken<ArrayList<CreateDoc>>() {}.getType());
docsList.forEach(System.out::println);
}
public static class CreateDoc {
DocMetData dMetaData;
DocContent dCont;
#Override
public String toString() {
return this.dMetaData.toString() + " " + this.dCont.toString();
}
}
public static class DocMetData {
String docName;
String docType;
#Override
public String toString() {
return "name: " + this.docName + " type: " + this.docType;
}
}
public static class DocContent {
String data;
#Override
public String toString() {
return "data: " + this.data;
}
}
}
You can use GSON to parse the message into a JSONArray with JSONObjects. Then create a parser for each class to convert the fields from the JSONObject into Java objects. Similar question is anwered here.
I think the problem is you are trying to map json to CreateDoc instead of CreateDoc List. If you are using spring boot to manage rest layer in your application use #Requestbody List CreateDoc in the method to convert your json. This will use Jackson converter internally. Otherwise you can use Jackson converter jar to convert your json to objects.

Jackson JSON array accessing

I have a Json file like this:
[{
dname: "xxxx",
dage: "24"
}, {
dname: "yyyy",
dage: "26"
}]
Target:
I want to access them as an array
Search through the names in the JSON file to look for a particular name
Same for age.
What I did:
file name : DtExtract.java
public class DtExtract{
public static ObjectMapper mapper = new ObjectMapper();
private Dtmain[] dtmain =mapper.readValue(new File("file location"), TypeFactory.defaultInstance().constructArrayType(D tmain.class));
public DtExtract() throws IOException{}
public String getname(int i) throws IOException { String strname = dtmain[i].getjname(); return strname;}
public String getage(int i) throws IOException { String strage = dtmain[i].getjage(); return strage;}
}
class Dtmain {
private String dname;
private String dage;
public Dtmain(){}
public String getjname(){return dname;}
public String getjage(){return dage;}
public void setjname(String dname){ this.dname=dname;}
public void setjage(String dage){ this.dage=dage;}
public String toString(){ return "Student [ name" + dname +", age " +dage +"]";
}
============================
file name: Myclass.java
public class Myclass{
public static void main(String args[]) throws IOException {
DtExtract dtextract= new DtExtract();
for(int i=0; i< 2; i++)
{
if (dtextract.getname(i).equals("xxxx")) {System.out.print("Name matches");}
if (dtextract.getage(i).equals("24")) {System.out.print("Age matches");}
}
}
}
=============================
This is the abstract of a code that I have, but my question is:
Does this for loop is really accessing the JSON array elements?
Is there any other faster way to do this JSON parsing and comparison?
You can do it as follows. You need to call both methods from main method
Please note that I have added two methods to process the array. processJsonArrayJava8 will be faster compared to processJsonArrayJava7.
public List<Dtmain> readFromJson()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Dtmain>> mapType = new TypeReference<List<Dtmain>>() {};
List<Dtmain> jsonList = mapper.readValue(
"[{\"dname\": \"xxxx\",\"dage\": \"24\" },{\"dname\": \"yyyy\",\"dage\": \"26\" }]",
mapType);
return jsonList;
}
public void processJsonArrayJava7(List<Dtmain> jsonList) {
for(Dtmain obj : jsonList) {
// do what ever you want with obj
}
}
public void processJsonArrayJava8(List<Dtmain> jsonList) {
jsonList.parallelStream().forEach(obj->{
//do what ever you want with obj
});
}
Please also give better names to the methods.
public class SayHi {
public static void main(String args[]) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Person>> maptype = new TypeReference<List<Person>>() {};
List<Person> jsonTopersonList=mapper.readValue(new File("JSON_file_location"), maptype);
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Name"+i+":"+jsonTopersonList.get(i).dname);
}
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Age"+i+":"+jsonTopersonList.get(i).dage);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class Person {
public String dname;
public int dage;
public Person() {
}
public Person(String dname,
int dage) {
this.dname = dname;
this.dage = dage;
}
public String toString() {
return "[" + dname + " " + dage +"]";
}
}
I came up with this one to deserialize that json data.

Can xstream deserialize a complicated array?

I study xstream these days.
But I found the xstream json tutorial which in its homepage is very simple.
I have an array as follows:
{
"mails":[
{
"uid":"ZC2027-mXOmcAtkfiztS0sEeJlkU25",
"relatedCardNums":"8299,0000,1531|8299,0000,1531",
"houseHolder":"",
"subject":"no-subject",
"receiveTime":"2012-05-27 00:00:00",
"bankName":"上海银行",
"cards":[]
}
],
"dealedNum":330,
"nextRequestDelay":"1",
"percent":"0",
"filterNum":410,
"resCode":"01",
"dealedBillNum":43,
"resMsg":"正在解析"
}
I want to convert this json string to a GetMailsDataResponseDto, but I dont know how to do?
Could you help me out?
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.utils.FileUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class GetMailsDataResponseDto extends ResponseBaseDto{
protected int dealedNum;
protected String nextRequestDelay;
protected String percent;
protected int filterNum;
protected int dealedBillNum;
protected List mails = new ArrayList();
public List getMails() {
return mails;
}
public int getDealedNum() {
return dealedNum;
}
public String getNextRequestDelay() {
return nextRequestDelay;
}
public String getPercent() {
return percent;
}
public int getFilterNum() {
return filterNum;
}
public int getDealedBillNum() {
return dealedBillNum;
}
public void fromJson(String json){
try {
json = FileUtils.get_content("C:\\Documents and Settings\\Administrator\\workspace\\99fund_java\\src\\com\\fund\\etrading\\ebankapp\\base\\credit\\新建 文本文档 (2).txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = "{\"root\":" + json + "}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("root", this.getClass());
//xstream.addImplicitCollection(this.getClass(), "mails");
xstream.alias("mail", MailDto.class);
//xstream.aliasField("cards", MailDto.class, "cards");
//xstream.aliasField("currencyData", CardDto.class, "currencyData");
//xstream.aliasField("data", CurrencyDataDto.class, "data");
xstream.fromXML(json, this);
}
}
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.BaseDto;
public class MailDto extends BaseDto{
protected String uid;
protected String relatedCardNums;
protected String houseHolder;
protected String subject;
protected String receiveTime;
protected String bankName;
protected List cards = new ArrayList();
public String getUid() {
return uid;
}
public String getRelatedCardNums() {
return relatedCardNums;
}
public String getHouseHolder() {
return houseHolder;
}
public String getSubject() {
return subject;
}
public String getReceiveTime() {
return receiveTime;
}
public String getBankName() {
return bankName;
}
public List getCards() {
return cards;
}
}
thanks in advance!
If you want to convert json string to your custom class(ex.GetMailsDataResponseDto), I recommend Google Gson.
If you use Gson, yon don't need fromJosn() method in GetMailsDataResponseDto class.
If you only use json parsing and have experiences of java script, I recommend Djson parser(java library).
"Djson Parse version 0.8a" -- http://blog.indf.net/category/Apps/djson
j1.txt - tip: "none BOM & UTF-8"
....
public void fromJson(String json){
//(real-code)--start
//Var var = Djson.parse(json);
//(real-code)--end
//--test-code--start
Var var = null;
try {
var = Djson.parse(new File("d:\\j1.txt"));
} catch (IOException e) {
e.printStackTrace();
}
//--test-code--end
this.dealedNum = var.get("dealedNum").toInt();
this.nextRequestDelay = var.get("nextRequestDelay").toString();
this.percent = var.get("percent").toString();
this.filterNum = var.get("filterNum").toInt();
this.dealedBillNum = var.get("dealedBillNum").toInt();
for(int i=0; i<var.get("mails").size(); i++) {
this.mails.add(var.get("mails").get(i).toObject()); // MAP type setting...
}
}

equivalent to python's shelve module in Java

Is there any module in Java equivalent to python's shelve module? I need this to achieve dictionary like taxonomic data access. Dictionary-like taxonomic data access is a powerful way to save Python objects in a persistently easy access database format. I need something for the same purpose but in Java.
I also needed this, so I wrote one. A bit late, but maybe it'll help.
It doesn't implement the close() method, but just use sync() since it only hold the file open when actually writing it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class Shelf extends HashMap<String, Object> {
private static final long serialVersionUID = 7127639025670585367L;
private final File file;
public static Shelf open(File file) {
Shelf shelf = null;
try {
if (file.exists()) {
final FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
shelf = (Shelf) ois.readObject();
ois.close();
fis.close();
} else {
shelf = new Shelf(file);
shelf.sync();
}
} catch (Exception e) {
// TODO: handle errors
}
return shelf;
}
// Shelf objects can only be created or opened by the Shelf.open method
private Shelf(File file) {
this.file = file;
sync();
}
public void sync() {
try {
final FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.close();
fos.close();
} catch (Exception e) {
// TODO: handle errors
}
}
// Simple Test Case
public static void main(String[] args) {
Shelf shelf = Shelf.open(new File("test.obj"));
if (shelf.containsKey("test")) {
System.out.println(shelf.get("test"));
} else {
System.out.println("Creating test string. Run the program again.");
shelf.put("test", "Hello Shelf!");
shelf.sync();
}
}
}
You could use a serialisation library like Jackson which serialises POJOs to JSON.
An example from the tutorial:
Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for
mapping JSON data into plain old Java objects ("POJOs"). For example,
given JSON data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
It takes two lines of Java to turn it into a User instance:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
Where the User class looks something like this (from an entry on Tatu's blog):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}

Categories