How to store a json array with .NET? - javascript

I Have a json array like
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]
How can i pass(to the backend) and store(in db) that javascript object with asp.net??
EDIT:
OK to make it clearer, in some page, i got a javascript object
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
, how can i pass it to some handler (like using
`$.post({url:"handler.ashx", data:array})
??), then in backend how can i save it into database or load this array later??
OR:
I'll appreciate it if u teach me how to convert
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
into:
var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]';
EDIT2:
Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??

You have several options when dealing with JSON on .NET
You can simply keep the array as is in the DB and retrieve it as is and use it
You can parse it into an Object using JSON.NET Library
for example on the 2nd case you simple use the JSON.NET method:
Newtonsoft.Json.Converters.KeyValuePairConverter
Or be fancy and use a Custom Deserialize as it's really easy to pass to and from JSON.
Let's imagine that you are posting something like this:
$.post("myForm.aspx",
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}],
function() {
// all done.
});
This will be converted to A,B,C when requesting the data using Request.Form["name"] or simply Request["name"] so you should change all the naming convention first and then you can simple use Request["nameA"], Request["nameB"], etc...

You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.

The best way to do this is to de-serialize the json into object and save it to db as records.
Check JSON.NET library http://json.codeplex.com/
public class MyObj
{
public string name{get;set;}
public string value{get;set;}
}
void Main()
{
string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]";
IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json);
foreach(MyObj o in arr)
{
//add each object to db...
Console.WriteLine(o.name+":"+o.value);
}
}

Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.

Related

Converting json array to query string gives null

What I am trying to achieve is to send a json object as a querystring to an API.
The json object I have is:
{
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
}
I would like to convert this to something like ?Name=&ImageUrls=
However, when using $.param(json) I get the following:
?Name=Dlsajdsa&ImageUrls%5B%5D=%2FImages%2FFacility%2F8353%2F85e26a18-4366-4412-b37a-72d94f2ccda5.jpg
This result, on the API point of view, that the ImageUrls array is null.
What am I missing here?
you can try $.param(json,true)
Based on the documentation of jQuery.param, I'd say this is the piece of code you want to use:
var json = {
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
};
var recursiveDecoded = decodeURIComponent($.param(json));
// "Name=Dlsajdsa&ImageUrls[]=/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"
The query parameter is called ImageUrls%5B%5D, that means ImageUrls[], not ImageUrls as you expect.

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

Passing an array from javascript to ruby with sinatra

What I want to accomplish is to pass a 2D array from javascript to something that ruby will recognize. All objects are strings
I have been using gon-sinatra, but it doesn't do exactly what I need.
I can pass store the string I want to pass as gon.text doing
#temp = gon.text
array.push(#temp)
This doesn't work because it shows gon.text as a nil object type, when I want it as a string. gon.text.to_s returns an empty string, so when I try to display it, nothing happens. alert("<%= #temp %>") // displays an empty string
I'm at a bit of a loss here and don't know the best way to approach this. Would it be better to store the array as a json, and then read in the json using ruby instead?
Yes. Convert your array to json(a string) with js:
var data = JSON.stringify(yourArray);
Send the string to your ruby script. Then parse the string into an Array with ruby:
require 'json'
arr = JSON.parse(the_string)
In Javascript you do something like the following:
var myArray = [ ['str1','str2'], ['str3','str4'] ];
$.get('/endpoint', { myArray: myArray })
And your endpoint with sinatra would be:
get 'endpoint' do
myArrayStr = params[:myArray]
error!('invalid array') unless myArrayStr
#myArray = JSON.parse(myArrayStr)
gon.rabl 'goners/yourFile.rabl', :instance => self
end
And in your gon file you would reference this with:
alert(gon.myArray[0][0]); // str1

Deserializing JavaScript object instance

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
alert("Saving...");
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json"
});
}
}
I am creating Item instances in my app and then saving them to local storage like such:
Item item = new Item();
window.localStorage.setItem("itemKey", JSON.stringify(item));
On another page, or at another time, I am retriving that item from local storage like such:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
Unfortunately, the "save" function does not seem to get reached. In the console window, there is an error that says:
*save_Click
(anonymous function)
onclick*
I have a hunch that the "(anonymous function)" is the console window's way of saying "calling item.save(), but item is an anonymous type, so I am trying to access an anonymous function". My problem is, I'm not sure how to convert "var item" into an Item class instance again. Can someone please show me?
Short answer:
Functions cannot be serialized into JSON.
Explanation:
JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :
Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?
What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.
I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.
I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.
instead of doing this:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
do something like this:
// get serialized JSON
var itemData = window.localStorage.getItem("itemKey");
//instantiate new Item object
var item = new Item();
// extend item with data
$.extend(item, JSON.parse(itemData));
// this should now work
item.save();
this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.
the $.extend method is a utility method of jquery, but it is trivial to roll your own.
You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.
what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.
You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data
ajaxsend(this.data);
also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use
savestring(JSON.stringify(item.data));
which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:
var item = new Item;
item.data = JSON.parse(getjsonstring());
Disclaimer
Not a full time time J.S. Developer, answer may have some minor bugs:
Long Boring Explanation
As mentioned by #JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.
Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.
Short & quick Answer
Since you already encapsulate the data members of your object into a single field,
you may want to try something like this:
// create J.S. object from prototype
Item item = new Item();
// assign values as you app. logic requires
item.data.name = "John Doe";
item.data.description = "Cool developer, office ladies, love him";
// encoded item into a JSON style string, not stored yet
var encodedItem = JSON.stringify(item.data)
// store string as a JSON string
window.localStorage.setItem("itemKey", encodedItem);
// do several stuff
// recover item from storage as JSON encoded string
var encodedItem = window.localStorage.getItem("itemKey");
// transform into J.S. object
item.data = JSON.parse(encodedItem);
// do other stuff
Cheers.

Passing Array from Activity to Javascript

I know there a couple of threads similar to this one but they dont actually answer the above question.
Firts question: is it true that only primitives can be passed? (String, boolean,...)
Second question: if it is so. I have an array of String in my activiy and i need it to fill a html table in my WebView and apparently i need to use Javascript interface to do so. So the question is: How can i do that? Do I need to create a string in my activity, pass it to JS and once there recreate the array?
You could use JSON as format for your data. A simple way would be to use a lib like GSON http://code.google.com/p/google-gson/ which makes it easy to convert your ArrayList with own object-types to Strings.
Send that to your WebView via the Javascript-interface and use JSON.parse(Stringname) in JS to recreate your Array.
Best wishes,
Tim
Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.
Here is what I did.
#JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
JSONArray myArray = new JSONArray(array);
JSONObject myObj = new JSONObject(jsonObj);
...
}
where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'
"Do I need to create a string in my activity, pass it to JS and once there recreate the array?"
That's the way i resolved it in my case ; i appended a special character to each item in the list while building up the string and later split it up in JS.
var strings = get.list(); // long string from activity.
var item1 = strings.split("=")[0];
var item2 = strings.split("=")[1];
....
Or you could go for a library

Categories

Resources