Given a query string that contains simple types (string, date), arrays, and complex objects, how can I easily create the JSON represenation using Java?
For instance:
type=event&groups%5B%5D=a&groups%5B%5D=b&details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)
should produce:
{ type: 'event', groups: [ 'a', 'b' ], details: { client_time: 'Sat Jan 30 2016 18:38:57 GMT-0500 (EST)' } }
Such functionality exists in the Node.js Express framework (the result is readily available as request.query).
Im still unsure (per the comments on the question) that the original string is correctly formatted. I think some chars got moved around when you where replacing values with dummy data. I don't think there is a logical transition from your original string to the serialized string
Take a look at this
final String opString = "type=event&groups%5B%5D=a&groups%5B%5D=b&details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)";
System.out.println(URLDecoder.decode(opString, "UTF-8"));
which outputs
type=event&groups[]=a&groups[]=b&details[client_time]=Sat Jan 30 2016 18:38:57 GMT-0500 (EST)
Where is my interpretation of your string
final String myString = "type%3Devent%26groups%3D%5B%27a%27%2C%27b%27%5D%26details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)";
System.out.println(URLDecoder.decode(myString, "UTF-8"));
which output
type=event&groups=['a','b']&details[client_time]=Sat Jan 30 2016 18:38:57 GMT-0500 (EST)
I can logically work with that to produce the string you want
final String myStringDecoded = URLDecoder.decode(myString, "UTF-8");
System.out.println(myStringDecoded);
// Then we can break it down to its parts
// The & is used to operate values
String[] parts = myStringDecoded.split("&");
JsonObject json = new JsonObject();
for(String part: parts){
String[] keyVal = part.split("="); // The equal separates key and values
json.addProperty(keyVal[0], keyVal[1]);
}
System.out.println(json);
which results in
{"type":"event","groups":"['a','b']","details[client_time]":"Sat Jan 30 2016 18:38:57 GMT-0500 (EST)"}
I can improve on this answer to make it exactly what you want if my assumptions are correct
Related
This question already has answers here:
Binding XML using POJO and JAXB annotations
(2 answers)
Closed 7 years ago.
I am trying to write a method that accesses a database and then returns a string / object in the format of XML here is the method that I have so far. I have looked at POJO and I don't believe its what i am looking for. I need to loop through and retrieve each xml child node. then display it in the correct format.
15 public Object getAppointment(String patientid){
16 DB db = new DB();
17 List<Object> objs = db.getData("Appointment", "patientid='"+patientid+"'");
18 Patient patient = null;
19 Phlebotomist phleb = null;
20 PSC psc = null;
21 for (Object obj : objs){
22 patient = ((Appointment)obj).getPatientid();
23 phleb = ((Appointment)obj).getPhlebid();
24 psc = ((Appointment)obj).getPscid();
25 return obj;
26 }
27 return "";
28 }
I need to make the obj variable in the format of XML but I cant figure it out. Here is what it returns now.
Appointment[id=710, Date: 2004-02-01, Time: 13:00:00
Phlebotomist: Phlebotomist[id=110, Name: Elizabeth Corday]
Patient: Patient[id=220, Name: Alice Wonderland, Address: 201 Mt. Hope Avenue, Insurance? Y, DOB: 1985-10-12
Physician: Physician[id=20, Name: Dr. Fine]]
PSC: PSC[id=510, name= Outer Banks]]
Test: AppointmentLabTest[appointmentLabTestPK=AppointmentLabTestPK[apptid=710, labtestid=86900, dxcode=292.9]
Lab Test: LabTest[id=86900, Name: Blood Group & Rh Type, whole BloodCost: 15.0]
Diagnosis: Diagnosis[code=292.9, Name: Caffeine – Related Disorder NOS]]
I need it to look like this when it comes back from the database.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<AppointmentList>
<appointment date="2016-12-30" id="791" time="10:00:00">
<patient id="220">
<name>Alice Wonderland</name>
<address>201 Mt. Hope Avenue</address>
<insurance>Y</insurance>
<dob>1985-10-12</dob>
</patient>
<phlebotomist id="110">
<name>Elizabeth Corday</name>
</phlebotomist>
<psc id="520">
<name>Down Town</name>
</psc>
<allLabTests>
<appointmentLabTest apptointmentId="791" dxcode="307.3" labTestId="86609"/>
<appointmentLabTest apptointmentId="791" dxcode="292.9" labTestId="86900"/>
</allLabTests>
</appointment>
</AppointmentList>
See this questions: Binding XML using POJO and JAXB annotations.
You can create customs POJOs and annotate it with JAXB to obtain the desire output
I want to parse the data returned by Yahoo Finance API that is in CSV format. I want the output in company name: stock price format. I have downloaded the Yahoo API example, the code is below:
String[] symbols = new String[] {"INTC", "BABA", "TSLA", "AIR.PA", "YHOO"};
Map<String, Stock> stocks = YahooFinance.get(symbols);
output:
INFO: Parsing CSV line: N/A,\"INTC\",\"USD\",N/A,N/A,N/A,\"INTC\",100,\"INTC\",N/A,N/A,\"INTC\",500,\"INTC\",32.35,\"INTC\",N/A,\"INTC\",\"4/23/2015\",\"4:00pm\",N/A,N/A,N/A,N/A,N/A,32348700,N/A,N/A,31.61,34.01,\"INTC\",4736000000,\"INTC\",\"INTC\",N/A,\"INTC\",153.21B,\"INTC\",4730885000,\"INTC\",\"6/1/2015\",N/A,N/A,N/A,N/A,2.16,0.59,2.40,N/A,1.82,2.78,2.77,11.77,55.87B,24.19B,34.95
Apr 24, 2015 6:14:56 PM yahoofinance.quotes.QuotesRequest getResult
I want only the price of that company.
The output you are showing is the logging of the API.
You have all the requested Stock objects available in your stocks variable. If you want to print the price for each of them, you should do something like this:
String[] symbols = new String[] {"INTC", "BABA", "TSLA", "AIR.PA", "YHOO"};
Map<String, Stock> stocks = YahooFinance.get(symbols);
for(Stock s : stocks.values()) {
System.out.println(s.getName() + ": " + s.getQuote().getPrice());
}
Check out the javadoc to see which objects and methods are available in the API.
try something like this
import csv
import StringIO
raw_file = StringIO.StringIO("data1, data2, data3, ...")
reader = csv.reader(raw_file)
for FIELD1, FIELD2,FIELD3,FIELD4 in reader:
print FIELD2
In my app I am sending base64 encoded files in Json format. My code is:
JSONObject jsonRequest = prepareJsonObject(expense, contentUri);
String jsonString = jsonRequest.toString();
StringEntity se = new StringEntity(jsonString);
The jsonRequest object looks like this:
{
"category":"660",
"user":"458",
"dated_on":"Wed Mar 12 10:38:11 GMT+00:00 2014",
"description":"document",
"gross_value":"-2.0",
"currency":"GBP",
"attachment":{
"data":"<base64>"
"mimetype":"image/jpeg"
}
}
The problem is that jsonRequest.toString() is taking like 2 minutes for a 700Kb file.
Is there a way to make this quicker? Am I doing something wrong?
thanks.
EDIT: I am testing in an actual Nexus 4 running KITKAT.
For completion purpose, this is the code for prepareJsonObject(), which runs in less than 2 secs.
public static JSONObject prepareJsonObject(Expense expense, String contentUri){
JSONObject expenseJson = null;
try{
expenseJson = new JSONObject();
if(expense.getUserId()!=null) expenseJson.put("user", expense.getUserId().toString());
if(expense.getProjectId()!=null) expenseJson.put("project", expense.getProjectId().toString());
if(expense.getCurrency()!=null) expenseJson.put("currency", expense.getCurrency().toString());
if(expense.getGrossValue()!=null) expenseJson.put("gross_value", expense.getGrossValue().toString());
if(expense.getNativeGrossValue()!=null) expenseJson.put("native_gross_value", expense.getNativeGrossValue().toString());
if(expense.getSalesTaxRate()!=null) expenseJson.put("sales_tax_rate", expense.getSalesTaxRate().toString());
if(expense.getDescription()!=null)expenseJson.put("description", expense.getDescription().toString());
if(expense.getDated()!=null)expenseJson.put("dated_on", expense.getDated());
if(expense.getCategoryId()!=null) expenseJson.put("category", expense.getCategoryId().toString());
if(expense.getManualSalesTaxAmount()!=null)expenseJson.put("manual_sales_tax_amount", expense.getManualSalesTaxAmount().toString());
if(contentUri!=null){
JSONObject attachmentJson = new JSONObject();
String base64data = AttachmentsUtils.getBase64ForUri(Uri.parse(contentUri));
attachmentJson.put("data", base64data);
attachmentJson.put("content_type", AttachmentsUtils.getMimetypeFromContentUri(Uri.parse(contentUri)));
expenseJson.put("attachment", attachmentJson);
}
}catch(Exception e){
Log.e("ExpensesUtils", "Couldn't encode attachment: "+e.getLocalizedMessage());
return null;
}
return expenseJson;
}
I think this is because the toString pare the full content of your base64 data to handle unicode characters and escape some specific characters. You can see this in JSONStringer#string, which is called for every string value in your JsonObject when you call toString.
Of course, as your data is base64, you don't actually need this. So I think you will need to implement your own toString implementation, probably based on the JSONStringer without escaping
I have a large file which has 10,000 rows and each row has a date appended at the end. All the fields in a row are tab separated. There are 10 dates available and those 10 dates have randomly been assigned to all the 10,000 rows. I am now writing a java code to write all those rows with the same date into a separate file where each file has the corresponding rows with that date.
I am trying to do it using string manipulations, but when I am trying to sort the rows based on date, I am getting an error while mentioning the date and the error says the literal is out of range. Here is the code that I used. Please have a look at it let me know if this is the right approach, if not, kindly suggest a better approach. I tried changing the datatype to Long, but still the same error. The row in the file looks something like this:
Each field is tab separated and the fields are:
business id, category, city, biz.name, longitude, state, latitude, type, date
**
qarobAbxGSHI7ygf1f7a_Q ["Sandwiches","Restaurants"] Gilbert Jersey
Mike's Subs -111.8120071 AZ 3.5 33.3788385 business 06012010
**
The code is:
File f=new File(fn);
if(f.exists() && f.length()>0)
{
BufferedReader br=new BufferedReader(new FileReader(fn));
BufferedWriter bw = new BufferedWriter(new FileWriter("FilteredDate.txt"));
String s=null;
while((s=br.readLine())!=null){
String[] st=s.split("\t");
if(Integer.parseInt(st[13])==06012010){
Thanks a lot for your time..
Try this,
List<String> sampleList = new ArrayList<String>();
sampleList.add("06012012");
sampleList.add("06012013");
sampleList.add("06012014");
sampleList.add("06012015");
//
//
String[] sampleArray = s.split(" ");
if (sampleArray != null)
{
String sample = sampleArray[sampleArray.length - 1];
if (sampleList.contains(sample))
{
stringBuilder.append(sample + "\n");
}
}
i suggest not to use split, but rather use
String str = s.subtring(s.lastIndexOf('\t'));
in any case, you try to take st[13] when i see you only have 9 columns. might be you just need st[8]
one last thing, look at this post to learn what 06012010 really means
I am using jquery Datatables plugin. I followed the link http://www.codeproject.com/Articles/190718/jQuery-DataTables-and-J2EE-web-application-integra
I am passing a Date in the JSON object to the datatables plugin. The format from webservice call is like
"Sat Jan 10 00:08:00 EST 2009"
, I need to strip off the time, EST and the day, I mean it should look something like
"Jan 10, 2009"
and the column is sorted on the server side. All I need is to strip off the data on the fly on the client side. I am still in the process of learning datatables plugin, I am not sure of implementing this. Experts please point me to the right direction.
[Edit] Since it looks like the date comes back from the server as a string then you're easiest solution is probably a regular expression. Try this:
function reformatDate(dateStr) {
var r = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+.*?(\d{4})$/
, m = (''+dateStr).match(r);
return (m) ? m[1]+' '+m[2]+', '+m[3] : dateStr;
}
[Original] Assuming you are working with an actual Date object and you don't want to incur the overhead of a proper JavaScript date wrangling library (such as the excellent Datejs) you could format the date like so:
var formatDate = (function() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return function(dt) {
return months[dt.getMonth()] + ' ' + dt.getDate() + ', ' + dt.getFullYear();
};
})();
formatDate(new Date()); // => "Mar 15, 2012"
I'm not sure if you can do this with bServerSide set to true but you might be able to setup column definitions using the aoColumns option for the datatable and then apply column rendering via
fnRender: function (o, val) {
parse your date here...
return newDateString;
}