JSONSerializer to render a Java String Array - javascript

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.

Related

matching content of a file

I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp

How can I deserialize a JSON array into a native .net data structure?

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.

Add items to JSON objects

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.

What String format is acceptable to append to this JSON output?

I have an existing "blackbox" web service. I need to append a session ID to the end of that output so that Javascript and similar clients can resume the stateful session.
Given the output below, what is the correct syntax to append or prepend an arbitrary GUID, so that it can be properly deserialized as valid JSON?
Note This data below is perfect. If I can somehow add a "removable" bit of information, using JSON.NET the string GUID, that would be ideal.
Output from REST call
"{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}"
The output above comes from Chrome. I'm not sure if Chrome adds additional quotes, etc but when I debug System.String on the server, I see the same thing being sent to the WCF service.
The end-usage for this will be a Chrome and Firefox plug in
Well if I am correctly understanding:
You get JSON from a blackbox service. It contains some properties and values. You want to add a new property with some GUID and send it to browser.
If this is correct, try following:
var json=<WHAT YOU GET FROM SERVICE>;
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
obj.sid="this is the new session id"; //ADD NEW PROPERTY
var j=JsonConvert.SerializeObject(obj); //GET BACK JSON STRING WITH NEW PROPERTY
Of if you just want to add session id on client side (inside your plugin) the utilize JSON2 javascript library and use following code (as also suggested by Josh in comments):
var o = JSON.parse(<REST OUTPUT>);
o.sid = <YOUR SESSION ID>;
To convert back to JSON string.
var jsn = JSON.stringify(o);
There is no way to modify that particular response without breaking existing clients. If you can break existing clients, or if you are working with clients that you control, you could wrap the object in another object, setting two keys: GUID and data. For example:
var json = JsonConvert.SerializeObject(new {
data = foo,
GUID = bar,
});
Where bar is the GUID that you want to use, and foo is one of two things:
The JSON string from the response. This will result in the final object looking like so:
{
data: "{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}",
guid: "00000000-0000-0000-0000-000000000000"
}
And you would get at the data through two calls to JSON.parse (or the equivalent).
The deserialized object from the JSON response. This will result in the final object looking like so (most data removed for brevity sake):
{
data: {
sa: [],
sb: [],
sz: ""
},
guid: "00000000-0000-0000-0000-000000000000"
}
And you would access data through response.data.
Why any modification can break existing clients
Where the current response is an object, there are only a few ways to modify it:
Injecting a key into the object. This assumes that no client uses Object.keys() or in any way iterates the key set (e.g. for (k in obj)). While this may be true, this is an assumption.
Adding another object to the end: }, {. Doing so would require that the response be transformed into an array:
[{}, {}]
This would break any client that is assumes the response is an object.
Wrapping the current response in a surrounding object (as proposed above). This as well breaks any clients that assumes a certain structure for the response.
{data:{}, guid: ""}

create json string on client side

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/

Categories