Parse String into Java Objects - java

I need to convert Strings of this format into an Array of objects.
[{name=Nancy Chapman, email=nchapman0#comcast.net}, {name=Jimmy Fisher, email=jfisher1#photobucket.com}]
Is there any easy way to convert this without having to do it completely manually?
UPDATE:
I am pulling these values from a custom SQL database (Amazon Athena). And the custom JDBC does not support getArray() so it looks like I need to manually parse the columns that contain an Array of Structs. It is unfortunately a limitation of the DB and I have no control over it. This is the format the SQL database returns when I call getString() on the column.
SQL Table Definition
id (int)
threadid (int)
senderemail (string)
sendername (string)
subject (string)
body (string)
recipients (array<struct<name:string,email:string>>)
ccrecipients (array<struct<name:string,email:string>>)
bccrecipients (array<struct<name:string,email:string>>)
attachments (array<binary>)
date (timestamp)
Java Objects
MessageObj
public class MessageObj {
private int id;
private int threadId;
private String senderEmail;
private String senderName;
private String subject;
private String body;
private List<RecipientObj> recipients;
private List<RecipientObj> ccRecipients;
private List<RecipientObj> bccRecipients;
private List<File> attachments;
private Calendar date;
}
RecipientObj
public class RecipientObj {
private String email;
private String name;
}
Parsing the data.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// Retrieve table column.
int id = rs.getInt("id");
Integer threadId = rs.getInt("threadid");
String senderEmail = rs.getString("senderemail");
String senderName = rs.getString("sendername");
String subject = rs.getString("subject");
String body = rs.getString("body");
//How to convert recipients into ArrayList? rs.getArray("recipients") not supported.
//... Code here to add into an ArrayList of MessageObj.
}

Perhaps I'm misunderstanding your question but what you typed should work if you clean it up a bit so that it looks like this:
[{ name:"Nany Chapman", email:"nchapman0#comcast.net"},
{ name:"Nany Chapman", email:"nchapman0#comcast.net"}]
Rather than use the equal sign, use a colon and put quotation marks around your values.

Related

how to map fields name between Java object and JSON file using GSON library

I'm parsing JSON object to Java object but some fields are null.
results
//Printed object after parsing, some fields are null
{host_ip='null', open=false, host_fqdn='null', nmap_results='null', cvss_vector='cvss2#av:n/ac:l/au:n/c:c/i:c/a:c', cvss=10.0, attackvector='n', list_
of_ports=null, ports___port='null', plugin_family='Windows', scanner_name='Local Scanner', operating_system='null', plugin_name='Microsoft Windows XP Unsupported
Installation Detection'
Usage of Gson library:
for (int v = 0; v < splunk_results_as_Array.size(); v++)
{
String vuln_as_string = splunk_results_as_Array.get(v).toString();
Splunk_data splunkdata = new Gson().fromJson(vuln_as_string, Splunk_data.class); // parsing happens here
System.out.print("\n Splunk : Splunk Java Object created \n" + splunkdata.toString());
splunkdata.ports_to_List();
splunkdata.setDataType(dataType);
list_of_Hosts.add(splunkdata);
}
Json object as string
"result":
{"cvss_vector":"cvss2#av:n/ac:l/au:n/c:c/i:c/a:c","host-ip":"XX.XX.XX.XX","plugin_family":"Windows","scanner_name":"Local Scanner","plugin_name":"Microsoft RDP RCE (CVE-2019-0708) (uncredentialed check)","hostname":"XX.XX.XX.XX","cvss":"10.0","attackvector":"n","ports{}.port":"3389"}
}
as you can see the fields : host-ip and ports{}.ports do have value.
The classed used:
public class Splunk_data
{
private String host_ip;
private boolean open;
private String host_fqdn;
private String nmap_results;
private String cvss_vector;
private double cvss;
private String attackvector;
private String ports_port;
private String plugin_family;
private String scanner_name;
private String operating_system;
private String plugin_name;
}
I think what caused the problem is host_ip doesnot match host-ip but I Java not possible to use '-' so I used '_'.
is there a way how to fix this?
To use different name for the variable than the actual key in JSON, you can use #Serialized annotation.
#Serialized("host-ip")
private String host_ip;
This will work and parse your host-ip as string.

What is the way to insert a huge JSON data into a SQLite DB in android

I have a large json request, that is, it has around 50k rows with 15 columns that I have to insert into a SQLite DB with the same structure. This is, I have to copy the same data allocated in postgres db into my sqlite db within my app. Is there some efficient way to do it? is there some api or something that could help to the work?
I have to tell that I'm able to do with OMRLite with JSON datas that isn't large but when I try to do with a bigger ones I have my app crashes and has the out of memory error.
Please if you have some idea or some example that I could follow I will appreciate it a lot! thanks in advance!
You can also use Google's Official Gson Streaming Library.
Gson Streaming : Gson Streaming
JsonReader plays very important role to parse json using Streaming library.
Because the JSON is so large you can't load it completely in memory. Even using the standard JSONObject will result on out of memory on many devices.
What I've done in a similar situation was to use Jackson for parsing it. Jackson can do it from the stream so memory usage is not a problem at all. The downside is API which is not that straight forward to use compared to normal options.
Here is an example I found: Jackson Streaming
GSON stream works for me Gson - streaming but I have to say it takes his time, around 4 minutes for 68K rows with 10 columns for example. But anyway solves my issue. So I have this JSON responde:
- preciosArtPK: {
codLista: 1,
codArticulo: 11348,
cansiVenta: 1,
fecVigencia: 1435781252000
},
siglaVenta: "UN",
precioVenta: 0,
margenPct: 100,
codUsuario: 1,
vigente: "S",
nomModulo: "MIGRACION"
Above JSON is a part of an array response but I have those "preciosArtPK" to include in the serialization with gson. How could I do that? I have the class that handles my serialization:
#DatabaseTable(tableName = "preciosart")
public class PreciosArt {
public static final String PRECIOS_COD_LISTA = "_id";
public static final String PRECIOS_COD_ARTICULO = "cod_articulo";
public static final String PRECIOS_CANSI_VENTA = "cansi_venta";
public static final String PRECIOS_FEC_VIGENCIA = "fec_vigencia";
public static final String PRECIOS_SIGLA_VENTA = "sigla_venta";
public static final String PRECIOS_PRECIO_VENTA = "precio_venta";
public static final String PRECIOS_MARGEN_PCT = "margen_pct";
public static final String PRECIOS_COD_USUARIO = "cod_usuario";
public static final String PRECIOS_VIGENTE = "vigente";
public static final String PRECIOS_NOM_MODULO = "nom_modulo";
#DatabaseField(id = true, unique = true, columnName = PRECIOS_COD_LISTA)
private Integer codLista;
#DatabaseField(unique = true, columnName = PRECIOS_COD_ARTICULO)
#SerializedName("codArticulo") // probar
private Integer codArticulo;
#DatabaseField(unique = true, columnName = PRECIOS_CANSI_VENTA)
private Integer cansiVenta;
#DatabaseField(unique = true, columnName = PRECIOS_FEC_VIGENCIA)
private Long fecVigencia;
#DatabaseField(columnName = PRECIOS_SIGLA_VENTA)
#SerializedName("siglaVenta")
private String siglaVenta;
#DatabaseField(columnName = PRECIOS_PRECIO_VENTA)
#SerializedName("precioVenta")
private Double precioVenta;
#DatabaseField(columnName = PRECIOS_MARGEN_PCT)
#SerializedName("margenPct")
private Float margenPct;
#DatabaseField(columnName = PRECIOS_COD_USUARIO)
#SerializedName("codUsuario")
private Integer codUsuario;
#DatabaseField(columnName = PRECIOS_VIGENTE)
#SerializedName("vigente")
private String vigente;
#DatabaseField(columnName = PRECIOS_NOM_MODULO)
#SerializedName("nomModulo")
private String nomModulo;
but this does't fill those fields (codArticulo, cansiVenta and fecVigencia). I read about to deserialize these json formats making another class of it, so I did the same:
#SerializedName("codLista")
private Integer codLista;
#SerializedName("codArticulo")
private Integer codArticulo;
#SerializedName("cansiVenta")
private Integer cansiVenta;
#SerializedName("fecVigencia")
private Long fecVigencia;
Problem is: how could I fill those field with my json deserialized? I use OMRLite to do the work, this class is for that purpose:
public long updatePreciosart(PreciosArt preciosArt){
long resultUpdate = -1;
try {
getHelper().getPreciosartDao().createOrUpdate(preciosArt);
resultUpdate = 0;
} catch (SQLException e) {
e.printStackTrace();
resultUpdate = -1;
}
return resultUpdate;
}
Hope you understand what the problem is and hope you help me with that! thanks again!

How to make JTextField into String/Long?

Currently Having my fields like that:
final JTextField PID = new JTextField("Product ID", 7);
frame.getContentPane().add(PID);
My method:
public StockItem(Long id, String name, String desc, double price) {
this.id = id;
this.name = name;
this.description = desc;
this.price = price;
}
Trying to use this method with values from my JTextFields, but it does not allow to use JTextFields under my Long/String/double places.
Is there any way how I could convert my JTextFields into the required things without editing my Method.
You should use the text field text and parse it.
long l = Long.parseLong(PID.getText());
double d = Double.parseDouble(PID.getText());
Yes, you can use PID.getText() to get the text, and then you can convert it to whatever you want, like this:
try{
long id = Long.parseLong(PID.getText());
String name = PNAME.getText();
String description = PDESC.getText();
double price = Double.parseDouble(PPRICE.getText());
}catch(Exception e){}
I have used the try-catch block because if the user enters something else instead of long in the PID, then it will catch the exception.

iterate result set to create object as required

Hello guys.I have following result set and now i want it to be saved in a java bean.I have two java beans(pojo).
public class Topic{
private int topic_id;
private String topic;
private List<SubTopic> subTopicList;
//getter setter
}
and
public class SubTopic{
private int sub_topic_id;
private String sub_topic;
//getter and setter
}
Now i want to set my Topic object in such a way that it contains one topic and list of all its subtopic.But i am having problem on iterating the result set.To make it more clear a Topic object that includes Cardiology should have,
topic_id=73
topic=Cardiology
List<SubTopic> subTopic=//this includes id and name of SubTopic and SubTopic2
Same another object should be for Allergy,Athma,Immunology.
ResultSet rs = pstmt.executeQuery();
//now how to iterate rs to create list of topic object in required way
Use a map to store your topics:
Map<Long, Topic> topicsById = new HashMap<>();
while (rs.next()) {
Long topicId = rs.getLong(1);
String topicName = rs.getString(2);
Long subTopicId = rs.getLong(3);
String subTopicName = rs.getString(4);
Topic topic = topicsById.get(topicId);
if (topic == null) {
topic = new Topic(topicId, topicName);
topicsById.put(topicId, topic);
}
topic.addSubTopic(new SubTopic(subTopicId, subTopicName);
}
Collection<Topic> allTopics = topicsById.values();

How to map a non-persistent user defined class so that Hibernate will load bean with instance from SQLQuery

I am new to hibernate and am having difficulty trying to get it to work for anything other than a direct table mapping scenario. Basically, I have a user defined Java class called: BookInvoice. This class is a non-persistent (not a db table) and uses columns from previously defined and Annotated) db tables. Every time I try to label it as an #Entity it tells me I cant because it is not an existing db table. How do I map it so that I dont get the
Unknown entity: com.acentia.training.project15.model.BookInvoice
error message that I have been experiencing.
My sql queries are good and I am able to get the info from the db; however, they come back as class Object and I am not permitted to cast them into my desired BookInvoice class in order to send it back to the calling method. Below pls find snipets of my work thus far . . .
Please note all of my regular classes that conform to existing db tables queries work fine, it is just the ones that are non-persistent that I am having issues with.
PurchaseOrderInvoiceDAO:
List<BookInvoice> bInvoiceList = null;
final String bookInvoiceQuery =
"SELECT Books.ID, PO_Details.QUANTITY, Books.ISBN, Books.TITLE, Books.AUTHOR, Author.Name, Books.PUBLISHED, Books.COVER, Books.SERIES, Books.SERIES_NO,\n" +
" Books.SUBJECT_ID,Books.PRICE\n" +
" FROM Purchase_Order, PO_Details, Books, Author\n" +
" WHERE Purchase_Order.ID=?\n" +
" AND Purchase_Order.ID=PO_Details.PO_ID\n" +
" AND PO_Details.Book_ID=Books.ID\n" +
" AND Books.AUTHOR=Author.ID";
Query bookInvoicQ = getSession().createSQLQuery(bookInfoQuery).addEntity(BookInvoice.class);
bookInvoicQ.setInteger(0, id);
bList = (List<Books>) bookInvoicQ.list();
BookInvoice class:
public class BookInvoice {
Integer id = null;
Integer quantity = null;
String isbn = null;
String title = null;
Integer authorId = null;
Date publishedDate = null;
String cover = null;
String series = null;
Integer seriesNo = null;
Integer subjectId = null;
Double price = null;
public BookInvoice(final Integer id, final Integer quantity, final String isbn, final String title,
final Integer authorId, final Date publishedDate, final String cover,
final String series, final Integer seriesNo, final Integer subjectId, final Double price) {
this.id = id;
this.quantity = quantity;
this.isbn = isbn;
this.title = title;
this.authorId = authorId;
this.publishedDate = publishedDate;
this.cover = cover;
this.series = series;
this.seriesNo = seriesNo;
this.subjectId = subjectId;
this.price = price;
}
public BookInvoice(){}
public Integer getId() {
return id;
}
etc. . . .
Stack Trace Snippet:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Unknown entity: com.acentia.training.project15.model.BookInvoice
File: org/hibernate/impl/SessionFactoryImpl.java
Line number: 693
Stacktraces
org.hibernate.MappingException: Unknown entity:
com.acentia.training.project15.model.BookInvoice
org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.getSQLLoadable(SQLQueryReturnProcessor.java:335)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processRootReturn(SQLQueryReturnProcessor.java:376)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processReturn(SQLQueryReturnProcessor.java:355)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.process(SQLQueryReturnProcessor.java:171)
org.hibernate.loader.custom.sql.SQLCustomQuery.(SQLCustomQuery.java:87)
org.hibernate.engine.query.NativeSQLQueryPlan.(NativeSQLQueryPlan.java:67)
org.hibernate.engine.query.QueryPlanCache.getNativeSQLQueryPlan(QueryPlanCache.java:166)
org.hibernate.impl.AbstractSessionImpl.getNativeSQLQueryPlan(AbstractSessionImpl.java:160)
org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:157)
com.acentia.training.project15.bo.PurchaseOrderInvoiceBO$PurchaseOrderInvoiceDAO.getById(PurchaseOrderInvoiceBO.java:196)
...
Ok! Finally broke down and talked to my supervisor about this. He explained that I am doing like waaaaaay to much extra work on this.
Basically, if I set the #Entity class/DB mappings up correctly then they will get all of the right information (ie. #OneToMany, etc.) from the mappings of the classes that correspond directly to the DB tables. Basically, Hibernate will go down as many levels (PO_Details ->Payments->Books, etc) they would give me all the additional information that I need and I wouldn't need to create my own custom classes.

Categories

Resources