In JavaScript I can define the following collection with keys awaiting values
var items = {
'book':null,
'pen':null,
'pencil':null,
'chicken':null,
'wallet':null
};
Then when I am ready to add values to my collection, I can do for instance
for(var p in items){
if(some condition){
items[p]=someValue;
}
}
Is there a way to do this with the same level of efficiency in java?
I know that in old Java I can combine a Map and a List to accomplish this, but are their new data structures in Java that can handle this? I am talking about Java 7 (or 8) perhaps? I am using Google App-Engine for my Java.
You could try it this way, if you're looking for the same style.
HashMap<String, String > items = new HashMap<String, String>(){{
put("book",null);
put("pen",null);
}};
Later you can put again with keys.
items.put("book", "Some Bible");
It seems you are new to Java and both Collections. I'm highly recommend you to read the about HashMap more before proceeding.
EDIT: Updated my answer based on the latest comments.
You could perfectly use a HashMap to achieve the same effect. To iterate over the existing keys, use the Map#keySet method.
Map<String, String> map = new HashMap<String, String>();
map.put("book", null);
map.put("pen", null);
for (String key : map.keySet()) {
map.put(key, "Some Value");
}
System.out.println(map);
Related
I have a Java array containing 5 strings. I want to plot this data using Flot Charts and thus I want to transfer it using render(array) from a Java file to an html file that will need Javascript. I have tried many things, and some users suggested me to just pass it to JSON in the Java file and then render it to make it easy to "digest" to Javascript.
One of the methods I've used is the following one:
JSONSerializer TestSerializer = new JSONSerializer();
String test = TestSerializer.serialize(array);
render(test);
I've tried to store it in a String test[] element (as an array), but it recognises the result to the serialization as a unique variable... However, the result I obtain when later on I assign into a variable ${test} in the html file to which I've done the render is the following one:
["Hello","Bye","Hi"]
With the strings "Hello", "Bye" and "Hi" placed like that, which is absolute garbage and is not useful to treat it with Javascript. Furthermore, if instead of render(array) I type renderJSON(array), all the html page goes blank but the array shows PERFECTLY as I want it, but obviously it is the only thing displayed in the content.
Do any of you have any idea of how to "transform" it or what could I do to get the desired ["Hello", "Bye", "Hi"] array in Javascript? Thanks!
Your question is not very clear.
So if I understood you right, you want something like a key:value relation.
Yes, you can do it with JSON and I also recommend you to use JSON.
The easy way is to use some library to do the parsing (Java->JSON) for you. I recommend you Gson.
An easy example with Gson, let's say you have a List of 4 objects type Person.
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then, you add each person to a List
Person john = new Person("John");
Person mark = new Person("Mark");
Person maria = new Person("Maria");
Person beth = new Person("Beth");
List<Person> personList = new ArrayList<>();
personList.add(john);
personList.add(mark);
personList.add(maria);
personList.add(beth);
Now comes the parsing, let's use Gson.
Gson gson = new Gson();
String jsonString = gson.toJson(personList);
At this point you already have the String with the JSON code in it. As I'm not sure if you just want the JSON String or the actual JSON Object, in case you want the JSON Object you can do the following:
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonString).getAsJsonArray();
They both hold the same information, but one in a String and the other in a JSON Object.
To make sure, you can do:
System.out.println("String: " + jsonString);
System.out.println("JSONArray.toString(): " + jsonArray.toString());
Which will print:
String: [{"name":"John"},{"name":"Mark"},{"name":"Maria"},{"name":"Beth"}]
JSONArray.toString(): [{"name":"John"},{"name":"Mark"},{"name":"Maria"},{"name":"Beth"}]
PS; If you want to change the key to something else you just need to change it on the Person class. Lets say you don't want you key to be as "name" but "firstName". You just go to the Person class and change the variable name to firstName
PS2; Using a parsing library for such a small example may look like an overkill but when your JSON object gets a little bit more complex it is a time saver.
I have JSON that looks like this:
{
"records": [{
"skills": "",
"u_past_assignment_groups": "",
"urgency": "3",
"correlation_id": "",
"u_program_name": "",
"u_software_name": "",
"group_list": ""
}]
}
(This is a truncated version.) But the point is that it is a single element array of key,value pairs.
In native JavaScript it is a very straightforward step to use JSON.parse or eval in order to convert this JSON to an actual array of key/value pairs, but, in .Net I cannot figure out how to deserialize this JSON into anything meaningful. I have tried every permutation I can come up with of JavaScriptSerializer.Deserialize and JavaScriptSerializer.DeserializeObject. No matter what I try I continue to get some sort of error about being unable to deserialize or being unable to cast. Can someone look at this code snippet and tell me how (in native .Net) I can deserialize this into a list or array of key/value pairs?
Do I have to create my own object to store this data? I mean, I'd hate to have to do that. It looks like it should easily conform to a native .net data structure.
//process response
Stream respStream = resp.GetResponseStream();
StreamReader respReader = new StreamReader(respStream);
string response = respReader.ReadToEnd();
respStream.Close();
JavaScriptSerializer jsDes = new JavaScriptSerializer();
//***This is the part I can't figure out.***
var objResp = jsDes.DeserializeObject(response);
Dictionary<string, string>[] dicResp = (Dictionary<string, string>[])objResp;
//******************************************
pOutput.InnerText = "Incident Number: " + dicResp[0]["key"];
You didn't say if you can use third party libraries, but I think Json.NET is better (more features and performance) than the JavascriptSerializer. You could acomplish what you want by using:
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
More about Json.Net: http://james.newtonking.com/json
This should work. I pasted your example in the input.txt file.
string json = File.ReadAllText("input.txt");
JavaScriptSerializer jsDes = new JavaScriptSerializer();
Dictionary<string, object> objResp = (Dictionary<string, object>)jsDes.DeserializeObject(json);
Object[] records =(Object[])objResp["records"];
Dictionary<string,object> results= (Dictionary<string,object>) records[0];
Console.WriteLine(result["urgency"]);
I presume that it's complex to read because of your JSON structure. You have "records" as the first entry in an empty array (you open and close the JSON with {}).
Further, inside records, you have another unindexed array whose first entry is the actual dictionary that contains your key/value pairs.
I am currently working on a ASP.Net MVC Razor application.
in my controller, I load two dictionaries with data and place them in a ViewModel as follows:
public Dictionary<String, List<String>> EngineerSchedule { get; set; }
public Dictionary<String, List<String>> WeeklySchedule { get; set; }
when in the view, I traverse the dictionaries to retrieve the List objects at every Key, I then change this String List into an Array and send them to a JavaScript function.
In my Js function, I would like to assign the above array to JS variables, when doing so, the JS variables become an array where the index holds the entire array from the function call.
Also, the params become an array of Chars
Any advice to why this happens will be greatly appreciated!
Code in View:
#foreach(var week in Model.WeeklySchedule)
{
var key = week.Key;
var values = week.Value.ToArray();
string[] eng = { };
foreach (var item in Model.EngineerSchedule)
{
if (item.Key == key)
{
eng = item.Value.ToArray();
}
}
#: gatherTimes('#Html.Raw(Json.Encode(key))', '#Html.Raw(Json.Encode(values))', '#Html.Raw(Json.Encode(eng))');
//In here, both values and engs are Array of the correct type and length
}
function gatherTimes(weekKey, values, engs)
{
var week =[];
var eng = [];
week[week.length] = values;
eng[eng.length] = engs;
for(var i = 0; i < engs.length; i++)
{
alert(engs[i]); //Outputs single chars, rather then the string values
alert(eng[i]); //Outputs an array with the length of all the chars from engs, but this array only has one value, which is the entire array from Engs
}
}
One way to inject server side information into the JavaScript portion of your application is "stringifying" the .Net object and calling JSON.Parse on the client side.
If you have the Json.NET nuget package from Newtonsoft you can use the static method JsonConvert.SerializeObject()
to turn almost any C# data structure into a JSON string.
After you place that string of JSON into your view using the templating feature of the Razor view engine, you can store it to a variable like so:
var engineerString = #JsonConvert.SerializeObject(Model.EngineerSchedule);
var dictionary = JSON.parse(engineerString);
As far as I can tell you are actually giving your javascript function strings as arguments since they are wrapped in quotes. Maybe there lies the confusion?
In my page I have an applet. I'd like to pass a some data to an applet function. I've found out how to do this and it worked fine for simple datatypes like strings but I'm having hard time with some nested data structures. I'm not sure what would be the right term for it — a list of dictionaries or an array of associative arrays. Here's a snippet of my JavaScript data structure is built.
var servers = []
servers.push({'id' : 1, 'ip' : '111.111.111.111'});
servers.push({'id' : 2, 'ip' : '222.222.222.222'});
$('testapplet').setWork(servers);
How do I access this in Java? I'd like to iterate over them and print them to the console? I tried the following code but I couldn't get it to work.
public void setWork(HashMap s[]) {
for (int i = 0; i < s.length; i++) {
HashMap item = s[i];
System.out.println(item);
System.out.println(item.get("ip"));
}
}
I'm not sure the Java/JavaScript bridge support anything other than primitive types.
You could try serialising to JSON, then pass that over the bridge:
...yourcode....
$('testapplet').setWorker(toJSON(yourvar));
Edit: as just mentioned... :)
There maybe a better solution, but you could JSON stringify the data in Javascript and then decode it in Java.
I am trying to create the JSON string / object that is equivalent to the following data on the server side. can somebody help?
Public Shared Function GetData() As List(Of Employee)
Dim list As New List(Of Employee)()
Dim newEmployee As New Employee()
newEmployee.EmployeeID = "1"
newEmployee.FirstName = "Sridhar"
newEmployee.Title = "Programmer"
newEmployee.BirthDate = "8/10/1979"
newEmployee.TitleOfCourtesy = "Programmer"
list.Add(newEmployee)
Return list
End Function
Employee is a class with the properties EmployeeId, FirstName, Title, Birthdate, TitleOfCourtesy.
Thanks,
sridhar.
Keep in mind that in Javascript there is no concept of a class, only objects. This also carries over into JSON. Look at this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
If you look at the first line, the "Employee" symbol does absolutely nothing for the JSON. Remember that we're dealing with ONLY objects.
Thats why this works, like you said.
[
{"EmployeeID":1,
"LastName":"Duggireddy",
"FirstName":"Sridhar",
"Title":"Programmer",
"TitleOfCourtesy":"Programmer",
"BirthDate":new Date(303091200000)}
]
To make this programatically, declare your employee objects, and just add them into an array, like so:
var employees = [];
employees.push(employee1); // you would use a loop, of course
employees.push(employee2);
...
var jsonString = parser.toJSON(employees); // or whatever you use.
That should give you a list of objects. Always ignore the class in JSON... .NET during the deserialization will attempt to coerce the object into that particular class. You only have problems if this fails - maybe because a variable is missing or of the wrong type.
Why not just use JSON.NET and let it handle encoding/decoding for you?
It will look like
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
Reference
I believe multiple instances of Employee in the JSON would look like this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
},
{
"EmployeeID":"2",
"FirstName":"Joe",
etc...
}
}
Maybe that is what you need?
There's a good jQuery plugin for JSON. It lets you go from a JavaScript object to JSON very easily.
http://code.google.com/p/jquery-json/