saving newtonsoft json response to isolatedstorage? - json

how can I save a list of Objects to isolatedstorage which is returned from a json call,
I already parse the result into a list of Objects, but I cannot seem to save it, I got a few xmlserialization issues, then I tried following this:
How to save a list of objects in isolated storage in wp7
but it led to a error
{System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: You must implement a default accessor on Newtonsoft.Json.Linq.JObject because it inherits from ICollection.

Opted to do the following:
private static void SerialiseAsJson(string textToSave, string fileName)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"..\..\NinjectModules\Fakes\FakeData\" + fileName))
{
file.WriteLine(textToSave);
}
}
Usage:
SerialiseAsJson(JsonConvert.SerializeObject([object to serialize]),"filename.JSon");

Related

Xamarin Forms - Saving object to access it later

I am using Xamarin Forms with Newtonsoft.JSON and Xam.Plugin.Settings plugins to save IDevice object as JSON to use it later.
First page:
private async void SelectBluetoothDevice(object sender, SelectedItemChangedEventArgs e)
{
string device = JsonConvert.SerializeObject((IDevice) e.SelectedItem);
AppSettings.AddOrUpdateValue("device", device);
await Navigation.PopAsync();
}
Here I simply make selected item to JSON string and save it. It works like it should be.
But the problem im facing comes whenever I try to deserialize from saved string.
string device = AppSettings.GetValueOrDefault("device", "");
if (!device.Equals(""))
{
Debug.WriteLine(device);
// This line produces error
IDevice dev = JsonConvert.DeserializeObject<IDevice>(device);
settingsDeviceName.Text = dev.Name;
}
Newtonsoft.Json.JsonSerializationException: Could not create an
instance of type Plugin.BLE.Abstractions.Contracts.IDevice. Type is an
interface or abstract class and cannot be instantiated. Path
'BluetoothDevice', line 1, position 19.
So I understand that IDevice is interface and my JSON string cant be deserialized nothing but into object. Any good ideas how to workaround it? Thanks!
This line JsonConvert.DeserializeObject<IDevice>(device); basically does this:
Read the JSON in device
Try to create the type of object you want to deserialize to, in this case, IDevice
Return you the new object with all the properties filled
The problem is with step 2. You can't create an instance of an interface. So you need to deserialize to a concrete object that implements IDevice.

XML to JSON in Camel Routing not working

I am trying to convert the XML message to JSON using camel router and save it into a file. Getting the XML message from the source and saving it to destination file etc are working. But when I try to convert to JSON, it did not work. I did not even throw any error/exception in logs. I am running on OSGI container
public class CamelRouter extends RouteBuilder {
#Override
public void configure() throws Exception {
from("file://C:/test/Sample.xml")
.routeId("file-to-file")
.log(LoggingLevel.INFO,"RouteID file-to-file !!!!! starting")
//From XML to JSON
.bean(CamelRouter.class, "convertXmlToJson")
.log(LoggingLevel.INFO,"From XML to JSON !!!!! Done")
.to("file://C:/test/JSONMessages")
.log(LoggingLevel.INFO,"Converted Message Saved successfully");
The bean method to convert XML to JSON convertXmlToJson is shown below
public String convertXmlToJson(String msg) {
log.info("NOW calling JSON conversion");
String jsonStr = null;
log.info("MESSAGE conversion starting : "); //After this message nothing happened
XMLSerializer xmlReader = new XMLSerializer();
log.info("MESSAGE before conversion : " + msg);
jsonStr = xmlReader.read(msg).toString();
log.info("JSON data : " + jsonObj.toString());
return jsonObj.toString();
}
Is anyone know why it is not executing the XMLSerializer portion. I tried this approach because the camel-xmljson's marshal().xmljson() call also give me the same results. Nothing happened after the xmljson() call in my camel routing.
Things that I checked are:
camel-xmljson feature up and running in OSGI
Dependencies mentioned in the Apache XmlJSON website added in my pom file, xom, camel-xmljson etc.
Am I missing anything here? Please help
The problem with your code route is that your bean component handler method resides within your route builder class, plus you invoke the bean component in a way that triggers another instantiation of that route builder class.
Personally, I would move convertXmlToJson to an appropriate utility class. That way you reduce mix of concern in the route builder and the bean component should work fine.
Alternatively, your route might work, if you invoke the bean component like this:
.bean(this, "convertXmlToJson")

Parse json and unable to access javascript object

I am passing a json object to the client side from java object with a time and value as attributes with gson
this.template.convertAndSend("/topic/123", gson.toJson(object, type));
and on the client side i have the following code where the json object data is stored in the body of the payload but I am unable to access the properties with obj.time or obj.value, it tells me undefined after it is parsed, I tried showing the entire 'obj' itself and the format seems fine however:
var subscription_callback1 = function(payload) {
var obj = JSON.parse(payload.body);
alert(obj);
};
output with alert(obj)
{"time":"3:00:34","value":"7989797"}
Nevermind solved. Since I am transfering STOMP protocol messages with the Spring 4 framework. I opted to use the Jackson2 message converter instead of directly using gson and it seems to work
#Configuration
#EnableWebSocketMessageBroker
public class MessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
messageConverters.add(new MappingJackson2MessageConverter());
return true;
}
then i directly put my java object into the send function instead of using gson to convert it as above
this.template.convertAndSend("/topic/123", event)

Convert grails domain object to JSON and manipulate it

I have a grails object that I am converting using def json = object as JSON. After I have it converted I want to add one more property called pin to the JSON which looks like the following.
[location:[lat:23.03, lon:72.58]]
Only way to do this so far seems like following
Serialize the DomainClass to JSON using grails.converters.json
Convert the JSON to string
Create JSONBoject using the string from Step 2
Add the property
Convert it back to String
Any other way to do this using grails.converters.json? I have tried using Gson but I do not want to go that route because I am getting many Circular Reference Errors
Try this:
domainInstance.properties + [pin: pinInstance] as JSON
I recently needed to do a similar thing. Some caveats:
This is using Grails 2.4.5
I use MongoDB as a backend. As such, I created an object marshaller for MongoDB domain classes. It is printed below, and you can wrap a similar marshaller for your domain class(es):
Marshaller:
class MongodbObjectMarshaller implements ObjectMarshaller<JSON> {
#Override
boolean supports(Object o) { return o?.properties?.dbo }
#Override
void marshalObject(Object obj, JSON converter) throws
ConverterException {
Map propertiesToOutput = obj.properties.dbo
propertiesToOutput.remove("_id") //don't print org.bson.types.ObjectId
propertiesToOutput.remove("version") //don't print gorm verson column
converter.build {
_id obj.id.toString()
propertiesToOutput.each{ entry ->
"$entry.key" entry.value
}
}
}
}
What that marshaller does, it allow in JSON output any of the domain class's properties. obj.properties.dbo is special to MongoDB, but for a regular domain class, you can just grab the properties and exclude the ones you don't need.
Then in my controller, this works:
domainInstance.pin = [location:[lat:23.03, lon:72.58]]
def content = tacticalCard as JSON
because my marshaller now picks up the pin property and prints it.

Is there a way to store instances of own classes in the ApplicationSettings of a Windows Store app?

In a Windows Store app I can only store WinRT types in the ApplicationSettings, according to the documentation. For roamed settings that should be held together I can use ApplicationDataCompositeValue. Trying to store an instance of an own class or struct results in an Exception with the message " WinRT information: Error trying to serialize the value to be written to the application data store. Additional Information: Data of this type is not supported". The term "trying to serialize" indicates that there must be some way so serialize a type for the application data API.
Does anyone know how I could achieve that?
I tried DataContract serialization but it did not work.
I think custom/own types are not supported.
See http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx:
"The Windows Runtime data types are supported for app settings."
But you can serialize your objects to XML and save as string... (see code below)
public static string Serialize(object obj)
{
using (var sw = new StringWriter())
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
public static T Deserialize<T>(string xml)
{
using (var sw = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sw);
}
}
https://github.com/MyToolkit/MyToolkit/blob/master/src/MyToolkit/Serialization/XmlSerialization.cs
Check out this class too:
https://github.com/MyToolkit/MyToolkit/wiki/XmlSerialization
Disclaimer: The above links are from my project