Get JSON data from RavenDB - json

I have an Asp.Net MVC3 application that use embedded RavenDB to store data.
The view needs json data that is now created by the controller in this way:
public ContentResult Data()
{
var res = JsonConvert.SerializeObject(DocumentSession.Query<DataObject>());
return new ContentResult { Content = res, ContentType = "application/json" };
}
Everything works fine but to me it seems inefficient because data that are stored in DB in JSON format is serialized in POCO and then deserialized again.
Is there a more direct way to get json data directly from the embedded db?

It's not inefficient at all. Keep in mind that internally, raven actually uses BSON - so you would have to translate it anyway. Also there are metadata fields. If you were to return it directly through your controller, you would have no opportunity to shape the response of the data and strip off the unwanted fields.
If you must continue with this line of thinking, you have two options:
You could use the DocumentStore.DatabaseCommands.Get() and related operations to return RavenJObjects that you could then translate JSON from.
You could talk directly to the Raven database over HTTP without using the raven client.
Neither of these are straightforward, and you are throwing away a lot of goodness of the Raven Client API. IMHO, any performance gain you were to achieve would be unnoticeable. I would stick with your current approach.
Also - If you are just trying to avoid having to serialize here, consider returning a JsonResult instead of a ContentResult. If you want to use Json.Net instead (per your other recent post), Here is a cleaner way to do it: http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

Related

Use case for a JSON file

I've used JSON a number of times within AJAX requests to perform asynchronous writes/reads of a database. I've been trying to better understand JSON and its uses within different programming environments and one of the questions I've been curious about is: what are the common use cases for JSON as external file (rather than just as an object that is passed within AJAX requests)?
More specifically, what are some use cases in which a .json file would be better suited than simply using temporary JSON objects to pass between AJAX requests? Any insight on this would be much appreciated.
I am not that familiar with AJAX etc., but JSON is so popular that many programming languages support it - not just Java and related languages.
In itself JSON simply holds information - it's merely a format for storing data.
It can often be used to transfer data between languages. Personally, I am also using JSON to store my objects to persistent data storages and then later on rebuild the objects alongside the .class schematics. For example, Google created GSON to easily turn objects into JSON and back. Very handy!
You should also think about: How do you transfer an object from one machine to another?
To sum it up: It's simple, it doesn't create massive overhead, it's even easy to read. And most important of all: So many tools offer JSON support.
Edit:
To show the simplicity of re-building from JSON, here's an example from my game:
public static Player fromJson(String json) {
if(json != null && !json.isEmpty()) {
return gson.fromJson(json, Player.class);
}
return new Player(); //no save game present. Use default constructor
}

Local persistent storage

I have a meteor react app and I need a way to save some info locally which will also be persistent. For example, if a user save a json, I want to use that same json even if the app is closed and reopen later. I tried groundDb but it requires server side as well. I need this feature to enable each user to save info such as game level. It will be great if I can use it on the web as well and not just for native versions. Thanks!
To join the pedants, here's the proper explanation:
You should first convert your object literal into JSON using the global JSON object and its stringify method:
let data = {a: 'some', b: 'data', c: null};
let json = JSON.stringify(data);
localStorage.setItem('data', json);
When you want to retrieve the data and use it in your application, you'll need to parse the JSON back into an object literal:
let json = localStorage.getItem('data');
let data = JSON.parse(json);
localForage
One option, which we use, is the npm package localforage which provides an asynchronous storage wrapper for localStorage and allows you to save data of any type. You can configure your store, and create multiple instances of local storage.
You can store any type in localForage; you aren't limited to strings like in localStorage.
Setting up localforage is similar to using localStorage except you have to use asynchronous calls:
Using Promises (Note you can use callbacks if you are not using the ES6 API)
Store your data
localforage
.setItem(
'state', data
)
.catch(console.error.bind(console))
Retrieve your data
localforage.getItem('state')
.then(data => /* ... */ )
.catch(console.error.bind(console))
Name your store
localforage.config({
name: 'myStore'
})
You can read more about localForage here.
yup it is quite easy. take the object you want and stringify it and then store in the local storage. JSON objects are string objects and not string per say. so when you store it to local storage it can not be stored as the object but the need to convert it to a json string.
to add : localStorage.setItem();
to retrieve : localStorage.getItem();
another good practice can be to, retrieve the data on log in, store it in an array and then store back into localstorage. so you wont have any junk data and its always up to date.
to clear : localStorage.clear(); Note: this will clear the entire localstorage.
also note that there is a size limit on the localstorage. most browsers allow 5-10 mb.
if you have large amounts of data you can also indexedDB. its fairly new but better for large amounts of data to be stored in the browser. for now i think only IE has a good implementation.
Use standard localStorage: https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
localStorage.setItem('xyz', JSON.stringify(object));
const object = JSON.parse(localStorage.getItem('xyz'));
It should be easy. Stringify the Object to make it a string then you save it. Follow this:
var dataToStore = JSON.stringify(data);
localStorage.setItem('someData', dataToStore);
You serialize the JSON when saving to localStorage:
var serializedData = JSON.stringify(data);
localStorage.setItem('dataKey', serializedData);
And deserialize it when retrieving from localStorage:
var serializedData = localStorage.getItem('dataKey');
var data = JSON.parse(serializedData);

Create JSON Object in React.js from Rest Service

I am looking for either guidance or a good example where I can map data coming from rest services to JSON "type" object which can then be used in a number of different react components.
The JSON Object will be used to map data from a few different rest services, which essentially hold very similar data which makes it better to use one object and then to bind the data to the respective React Components.
I am fairly new to React.JS and I have googled around to find a data mapper to JSON from Rest Service example.
Can anyone help?
You typically don't have to do too much, at least on the front end side. As long as the REST endpoint can return JSON responses you'll be fine. Just make sure you set the appropriate Content-Type headers in the request. Note that setting the header doesn't guarantee a JSON response, the server has to be able to send it in that format.
If you're creating the REST service yourself, you have many options. If you're using node, you can simply return a javascript object. If you're using some other language like Java, C#, etc., they come with libraries that can serialize objects into JSON for you. I use JSON.net when working with C#. In these cases, because the data will be returned as a string, you'll just need to JSON.parse() it upon receiving it and then set it to the appropriate React component's state.

JSON to NSManagedObject conversion

I get JSON from a web service which I need to save locally using Core Data. This is part of a sync operation which is performed after certain interval. I need to first convert JSON to NSManagedObject and check if it is already saved locally then just update existing otherwise insert new NSManagedObject.
An NSManagedObject being checked, whether it is saved already or not. can also have relations with other NSManagedObjects (which also need to be part of predicate)
Can anyone suggest any considerable lib to handle this deserialization/serialization from/to JSON <-> NSManagedObject.
i use RestKit for this purposes, it's pretty easy to use
#Eugen
RestKit seems complicated. I had to parse pretty complicated JSON and save in Core data. Also the data on server can change and in next parsing the local Core data values needs to be updated not inserted new.
But on the web service call, I need to authenticate by setting HTTP header user=access_token, password=mypassword.
There is only one method in RestKit to requesting and mapping directly to managedObject and only that method is not working properly while sending the request. I get 403 response. All the other methods which are not related to NSManagedObject authenticates and gets good JSON in the response.
I have wasted so much time trying to make RESTKIT work and now I feel I should try some simple way. Can anyone suggest any good lib or any other suggestions.
Thank you.
Concerning RestKit: I prefer doing web service calls as described here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
As to your deserialisation problem: You might want to convert the NSData object retrieved by the web service to a JSON structure like this:
NSMutableDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
Then you can use https://gist.github.com/pkclsoft/4958148 for populating a NSManagedObject with like this:
Entity *entity = [NSEntityDescription insertNewObjectForEntityForName:#"Entity" inManagedObjectContext:[self managedObjectContext]];
[entity populateFromDictionary:dict];
If the json structure and the structure of the NSManagedObject differ, you can manipulate the NSMutableDictionary before using it for populating the NSManagedOject.

Stream objects from MongoDB cursor into nodejs HTTP response

NOTE: I don't believe this question is a duplicate of this similar question because it is more specific.
I'm attempting to retrieve multiple objects from Mongo with the nodejs-mongodb-driver and write the objects to an HTTP response as JSON. The objects should be in the form of an array, but i don't want to call toArray() on the cursor because of the memory overhead and I try to avoid large JSON.stringify calls whenever possible.
var response = ... // an http response
collection.find().stream(JSON.stringify).pipe(response); // causes a malformed JSON string
The object in the browser appears as follow.
{"obj", "obj"}{"obj", "obj"} // clearly malformed
Is there an efficient way to do this?
I will explain the code you wrote so that you understand why it returns malformed JSON and why you probably need toArray() or the JSONStream libary from the answer you posted.
First collection.find() returns a Cursor object. At that point no data was read. Then, the .stream(JSON.stringify) call returns a readable Stream with the transformation function JSON.stringify. Still no data read.
The .pipe(response) call then reads the entire Stream to the end and for every object it calls the JSON.stringify function. Note that it does really call it for every single object seperately and therefore does not create an array. Instead you get your malformed JSON, object after object.
Now the answer in the question you posted as possible duplicate (Stream from a mongodb cursor to Express response in node.js) would work for you, but it requires an additional libary with a JSONStream. The JSONStream properly handles the CursorStream for JSON output. I don't know if that really reduces the overhead though, but you could try that.
Without an addition libary you will have to use toArray().