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/
Related
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);
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 a situation that I just cannot figure out how to do. I'm trying to add items to a JSON object that was sent from the controller.
Here's my models:
public class Model1
{
public Model2 item {get;set;}
public List<Model2> items {get;set;}
//
And in the page
var jsonData = #Html.Raw(JSON.Encode(Model))
This gives me the basic but empty model. Now in the page I fill in various fields and want to add the items into the model for posting. So:
jsonData.item.field1 = $("#field1").val();
Then I want to add to the list of items, but I cannot find anything that works:
jsonData.items.add(jsonData.item)
doesn't work throws an error.
jsonData.items.push(jsonData.item);
works but every item I add ends up the same. Meaning that when I add the second item there are two in the list but they have the same values. Any help would be appreciated.
As we know, Javascript can be used as OO language and classes and objects can be created on the fly in javascript.
Per my understanding, you are using below code to get class attributes in the JavaScript
var jsonData = #Html.Raw(JSON.Encode(Model))
When this JSON is returned to the client side, it is considered as single object.
So, you can declare a function, acting as class:
function Model2(jsonData ) {
this.name = jsonData.name;
this.discovered = jsonData.discovered;
};
var objModel2_1= new Model2(jsonData);
Now,
you can declare an array to add the objModel2.
var arrModel2=[];
// add new objects
attModel.push(objModel2_1);
Finally,
when you are done, you can use existing jsonData object to fill
i.e.
jsonData.item=objModel2_1;
jsonData.items=attModel;
Hope, this will help you.
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?
I have a JSON payload from a REST service that looks something like this:
var jsonify = JSON.stringify(theReturnedData);
console.log(jsonify) =
{
"f-012839": {
"name": "Bob",
"email": "asdf#gmail.com"
}
}
How do I access, for example, the email value without knowing what "f-012839" is?
Here is what I have tried so far without success:
var name = jsonify[0].name;
var name = jsonify.name;
The "f-012839" value is dynamic and I won't know what it is beforehand. It'd be nice if I could get to the "name" and "email" elements without having to know what the "f-012839" key would be. Or, is it possible to take a subset of the returned JSON, so that instead of having the above value, it could be something like this:
{
"name": "Bob",
"email": "asdf#gmail.com"
}
If that's possible, I should be able to get any of those values by simply doing the below, right?
var name = jsonify.name;
Any help would be greatly appreciated. Thanks SO!
for(var key in theReturnedData) {
theReturnedData[key] // This is the object you want access to
}
Update Also make sure to implement a check for each key. You need to filter out the properties that could be inherited from the objects Prototype (lots of frameworks add custom properties to object Prototypes. You can check that through Object.hasOwnProperty(property_name), so basically use this loop:
for(var key in theReturnedData) {
if(!theReturnedData.hasOwnProperty(key)) continue;
theReturnedData[key]
}
for(field in JSON.parse(jsonify)) {
firstObject = jsonify[field];
console.log(firstObject.name);
console.log(firstObject.email);
}