JSP array output - arrays

How can I get the below output in jsp?
[[1417165200000,28477.92],[1417165320000,28484],[1417165440000,28474.86],[1417165560000,28478.88]]
Both the values comes from a variables in jsp code.
I have tried:
Map<String, String> list = new HashMap<String, String>();
list.put(last_traded_price, price_date);
It gives me this:
{28779.4400=2014-11-28 12:58:00.0, 28794.5000=2014-11-28 01:24:00.0}
Please suggest me what I can use in jsp to get the desired output.
This is what I did in php,
$array_item[] = array(strtotime($price_date)*1000, (float)$last_traded_price);
Update 1:
while(rs.next()){
last_traded_price = rs.getString(1);
price_date = rs.getString(2);
child.add(last_traded_price);//1
child.add(price_date);//2
}

If you want this [[1417165200000,28477.92],[1417165320000,28484]] particular format then i would advice you to use json-simple.jar
so if whenever you want to create data in above format you need to write code as below :
JSONArray root = new JSONArray();
while(rs.next()){
JSONArray child= new JSONArray();
last_traded_price = rs.getString(1);
price_date = rs.getString(2);
child.add(last_traded_price);//1
child.add(price_date);//2
root.add(child);
}
System.out.println(root);
so for 1417165200000,28477.92 this pair you will have root as [[1417165200000,28477.92]]
if you want to add another pair just repeat the steps 1,2 and 3

Related

Unable to convert String type Array into Json

I am trying to convert Array output into Json but It returns me both output same.
Array Code:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
String[] myStringArray = new String[]{"a","b","c"};
System.out.println(myStringArray);
gson.toJson(myStringArray);
System.out.println("Json Output" + gson.toJson(myStringArray));
Output of Array :[a,b,c]
Output of Json : ["a,b,c"]
Above is just example of my data output. In actual I am using dynamic string array and adding 3 values per array index separated by comma. So each array index has 3 values like array[0]= ["value1,value2,value3"]
Expected Output : [{"key1":"value1","key2":"value2","key3":"value3" }]
Here's the solution of using Map
public String convertArraysIntoJson(List<String[]> myStringArrays){
List<Map<String, String>> maps = new ArrayList<>();
for(String[] myStringArray : myStringArrays){
Map<String, String> map = new HashMap<>();
for(int i = 0; i < myStringArray.length; i++){
map.put("Key"+(i+1), myStringArray[i]);
}
maps.add(map);
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
return gson.toJson(myStringArray);;
}

Iterate specific JSONObject with no keys

Can anyone help me how to iterate this kind of JSON
http://104.236.54.235/api/v1/preguntas
i need to get all stuff inside a table database, but no idea how.
Thnx
You can iterate over JSONArray and for each JSONObject get the keys like id,pregunta...etc.
JSONArray jAttrArr = new JSONArray(jsonString);
for(int j=0;j<jAttrArr.length();j++){
JSONObject jObject = jAttrArr.getJSONObject(j);
String id = (String) jObject.get("id");
String pregunta= (String)jObject.get("pregunta");
...
}

Sort an Array, populated by an IsolatedStorageFile text file seems to move the 0 entry

I have the code below that splits a text file from IsolatedStorage, populates an Array with the data, sorts it, and then assigns it as the source for a ListPicker:
var splitFile = fileData.Split(';');
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
However, it doesn't seem to populating the array correctly and the sorting doesn't appear to be working as expected either.
The testArray[0] is blank, when it should be populated. When the output is shown the entry that should be at [0] appears at the bottom.
BEFORE SORTING:
AFTER SORTING:
It's only in sorting the array that it seems to screw up the order.
UPDATE: I tried the suggested:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
This still results in the second screenshot, above.
When the app first ever runs I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
store.CreateDirectory("testLocations"); // Create a directory
IsolatedStorageFileStream rootFile = store.CreateFile("locations.txt"); // Create a file in the root.
rootFile.Close(); // Close File
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
string filePath = "locations.txt";
if (store.FileExists(filePath)) {
Debug.WriteLine("Files Exists");
StreamWriter sw =
new StreamWriter(store.OpenFile(filePath,
FileMode.Open, FileAccess.Write));
Debug.WriteLine("Writing...");
sw.WriteLine("Chicago, IL;");
sw.WriteLine("Chicago, IL (Q);");
sw.WriteLine("Dulles, VA;");
sw.WriteLine("Dulles, VA (Q);");
sw.WriteLine("London, UK;");
sw.WriteLine("London, UK (Q);");
sw.WriteLine("San Jose, CA;");
sw.WriteLine("San Jose, CA (Q);");
sw.Close();
Debug.WriteLine("Writing complete");
}
Then when I add to the file I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
byte[] data = Encoding.UTF8.GetBytes(locationName + ";");
string filePath = "locations.txt";
if (store.FileExists(filePath))
{
using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Append, store))
{
Debug.WriteLine("Writing...");
stream.Write(data, 0, data.Length); // Semi Colon required for location separation in text file
stream.Close();
Debug.WriteLine(locationName + "; added");
Debug.WriteLine("Writing complete");
}
}
I'm splitting using a ";" could this be an issue?
There's no problem with the sort: 'space' is considered to come before 'a', so it appears on top of the list. The real problem is: why do you have an empty entry to begin with?
My guess is that, when creating the file, you're separating every entry with ;, including the last one. Therefore, when parsing the data with the string.Split method, you're left with an empty entry at the end of your array.
An easy way to prevent that is to use an overload of the string.Split method that filters empty entries:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
I went a different way using IsolatedStorageSetting and storing Arrays/Lists to do what I wanted.

NullReferenceException while saving XML File with Linq

I keep getting a NullReferenceException at this line UserRoot.Element("User_ID").Value = User.User_ID.ToString();
What exactly am I doing wrong?
Here's the majority of the code for that method
if (File.Exists(Path2UserDB + User.User_ID.ToString() + ".db") == false)
{
File.Create(Path2UserDB + User.User_ID.ToString() + ".db");
}
XElement UserRoot = new XElement("User");
UserRoot.Element("User_ID").Value = User.User_ID.ToString();
UserRoot.Element("Full_Name").Value = User.Full_Name;
UserRoot.Element("Gender").Value = User.Gender;
UserRoot.Element("BirthDate").Value = User.BirthDate.ToString();
UserRoot.Element("PersonType").Value = User.PersonType.ToString();
UserRoot.Element("Username").Value = User.Username;
UserRoot.Element("Password").Value = User.Password;
UserRoot.Element("Email_adddress").Value = User.Email_Address;
XDocument UserDoc = new XDocument();
UserDoc.Save(Path2UserDB + User.User_ID.ToString() + ".db");
Thanks
I know that saving Usernames and Passwords in plain text is incredibly unsafe, but this is only going to be accessed by one process that I will eventually implement strong security
The Element("User_ID") method returns an existing element named <User_ID>, if any.
Since your XML element is empty, it returns null.
You should create your XML like this:
var userDoc = new XDocument(
new XElement("User",
new XElement("User_ID", User.User_ID),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
...
)
);
Alternatively, you can call the Add method to add a node to an existing element.
You are getting this error, because there is no XML element called User_ID under UserRoot to set its value. If you comment it out, you will get the same error on the next line and so on for every other Element, since you haven't added Elements with thos names. To create the tree that you want, try this:
XElement UserRoot =
new XElement("User",
new XElement("User_ID", User.User_ID.ToString()),
new XElement("Full_Name", User.Full_Name),
new XElement("Gender", User.Gender),
new XElement("BirthDate", User.BirthDate.ToString()),
new XElement("PersonType", User.PersonType.ToString()),
new XElement("Username", User.Username),
new XElement("Password", User.Password),
new XElement("Email_adddress", User.Email_Address)
);
The following MSDN link on XML Tree Creation with XElement will be of help.
You want to check if the value is null or empty before running methods on it.
if(!String.IsnullorEmpty(User.User_ID))
UserRoot.Element("User_ID").Value = User.User_ID.ToString();

How to convert SET to array in APEX?

I have map with key and value and my goal is to get list of 'key'.
I am thinking to get it to the array or List.
Got to the point where I have key values in the SET but haven't figure out
how to convert to the array.
below is my code:
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
//outputs values in the map
system.debug('=======values()==========>' + mmm.values());
//outputs key in the map
system.debug('=======keyset()===========>' + mmm.keyset());
//get keys in the type SET
SET<string> s = mmm.keyset();
//returns 4
system.debug('------------------------------------' + s.size());
s.arrayTo() //this method does not exist :(
Use List.addAll method?
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_methods_system_list.htm?SearchType=Stem
If not - you could always manually loop through the set...
Could you use:
Set keys = mmm.keySet();
List keyList = new List(keys);
You should always used generics for type safety.
Map<String, String> mmm = new Map<String, String>();
mmm.put('one', 'oneee');
mmm.put('two', 'twooo');
mmm.put('three', 'threeee');
mmm.put('four', 'fourff');
List<String> lstKeys = new List<String>(mmm.keyset());
System.debug('Output : '+lstKeys);
As per link : https://salesforce.stackexchange.com/questions/5447/is-there-a-difference-between-an-array-and-a-list-in-apex .
This solution will work.
A quick and simple way to do this would also be:
new List<String>(mmm.keySet());
//or
new String[mmm.keySet()];
In some code I wrote recently I've got a Set<String> and am passing it into a method that takes a List<String> with methodName( new List<String>(setVariable) ); or methodName(new String[setVariable] );
Yes I know the post is 11+ years old... but it is also what comes up when searching so I put my answer here.

Resources