I need to save a list of ParseObjects to disk in C#, and was wondering if anyone had any recommendations on how to achieve this.
I am sure that the Parse .NET SDK has a means of converting ParseObjects to/from JSON since that is the format used during transit to parse server, but I haven't been able to find any public methods to do this :(
Hopefully someone has an answer for what should be an easy question! :)
If you are using Newtonsoft You can do this
var jsonString = JsonConvert.SerializeObject(yourObject);
using (StreamWriter writer =
new StreamWriter("SerializedObject.json"))
{
writer.Write(jsonString);
}
To read the JSON file you can do this
using (StreamReader reader =
new StreamReader("SerializedObject.json"))
{
string jsonString = reader.ReadToEnd();
YourObject ObjectFromJson = JsonConvert.DeserializeObject<YourObject>(jsonString);
}
I think you can use ToString() method for parsing. You override the ToString() method in your Class and write parsing code on it.
For more information you can look into below link
https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx
Related
I need to save Google protobuf IMessage object into json file, using C#.
here is sample code:
using (var input = File.OpenRead(protodatFile))
{
string jsonString = null;
message.MergeFrom(input); //read message from protodat file
JsonFormatter formater = new JsonFormatter(
new JsonFormatter.Settings(false));
jsonString = formatter.Format(message);
System.IO.File.WriteAllText(jsonFile, jsonString);
}
This uses the JsonFormatter from the Google Protobuf library.
The problem: all json content is stored in one line. when file is quite big(>50 MB) it is hard to open/view in text editor.
What is the best way to make indented jsonFile here?
As an extremely inefficient workaround, one can use Json.NET to re-format the Protobuffer Json:
// Re-Parse the one-line protobuf json string into an object:
object parsed = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
// Format this object as JSON with indentation:
string jsonWithIndent = Newtonsoft.Json.JsonConvert.SerializeObject(parsed, Newtonsoft.Json.Formatting.Indented);
Since the original question asked about a 50MB file, this is probably a bad solution for such large-ish files, but given that I couldn't find anything on JsonFormatter.Settings, it was what I reached for.
As of version 3.22.0 of Google.Protobuf you can use the following:
JsonFormatter formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithIndentation());
output = formatter.Format(msg);
See here for the corresponding issue: https://github.com/protocolbuffers/protobuf/pull/9391
This is more of a theoretical question, but I am curious what the difference between these two methods of reading a file is and why I would want to choose one over the other.
I am parsing a JSON configuration file (from local disk). Here is one method of doing it:
// Uses JSON.NET Serializer + StreamReader
using(var s = new StreamReader(file))
{
var jtr = new JsonTextReader(sr);
var jsonSerializer = new JsonSerializer();
return jsonSerializer.Deserialize<Configuration>(jtr);
}
...and, the second option...
// Reads the entire file and deserializes.
var json = File.ReadAllText(file);
return JsonConvert.DeserializeObject<JsonVmrConfigurationProvider>(json);
Is one any better than the other? Is there a case where one or the other should be used?
Again, this is more theoretical, but, I realized I don't really know the answer to it, and a search online didn't produce results that satisfied me. I could see the second being bad if the file was large (it isn't) since it's being read into memory in one shot. Any other reasons?
by reading the code you found that deserializaton from a string finally reach:
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, "value");
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
jsonSerializer.CheckAdditionalContent = true;
using (var reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
That is the creation of a JsonTextReader.
So the difference seems to effectively be the handling of huge files.
-- previous comment temper:
JsonTextReader overrides JsonReader.Close() and handles the stream (if CloseInput is true), but not only.
CloseInput should be true by default as the StringReader is not explicitly disposed in previous fragment of code
With File.ReadAllText(), the entire JSON needs to be loaded into memory first before deserializing it. Using a StreamReader, the file is read and deserialized incrementally. So if your file is huge, you might want to use the StreamReader to avoid loading the whole file into memory. If your JSON file is small (most cases), it doesn't really make a difference.
I am trying to read a response from a server that I receive when I send a POST request. Viewing fiddler, it says it is a JSON response. How do I decode it to a normal string using C# Winforms with preferably no outside APIs. I can provide additional code/fiddler results if you need them.
The fiddler and gibberish images:
The gibberish came from my attempts to read the stream in the code below:
Stream sw = requirejs.GetRequestStream();
sw.Write(logBytes, 0, logBytes.Length);
sw.Close();
response = (HttpWebResponse)requirejs.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
As mentioned in the comments, Newtonsoft.Json is really a good library and worth using -- very lightweight.
If you really want to only use Microsoft's .NET libraries, also consider System.Web.Script.Serialization.JavaScriptSerializer.
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
Going to assume (you haven't clarified yet) that you need to actually decode the stream, since A) retrieving a remote stream of text is well documented, and B) you can't do anything much with a non-decoded JSON stream.
Your best course of action is to implement System.Web.Helpers.Json:
using System.Web.Helpers.Json
...
var jsonObj = Json.Decode(jsonStream);
Right now I am programming a multiplayer card game in Silverlight
I am wondering how to store a object best binary in a sql database.
I have a GameState Object which contains the current state of a game between two players. I want to store this object in a sql database that both player can access and change it anytime.
How would you do that with Silverlight + RIA Services? Especially the part where you serialize the object in Silverlight.
Thanks
I would do the serialization on the server side. Add an Invoke operation to your RIA services domain context that accepts your GameState object. On the server side you can then use standard .NET serialization (personally I would recommend XML serialization instead of binary, but it shouldn't matter).
First, you can not possibly simply serialize something at the server. It must be serialized before it can be sent to the server. But it seems that perhaps you are making things too complicated/magical.
Given what you have said, I would start with by defining my GameState object (and any other object you need) inside the Entity Framework. Include any and all fields that are needed to save the state of the game. Then you should be able to have the framework create the needed tables.
Once you have done this, add a DomainService to the web project and when you compile the objects will then be available inside your Silverlight project.
Finally i decided to use XML serialization.
I found a great article about XML Serialization: http://www.ingebrigtsen.info/post/2008/11/29/Serialization-in-Silverlight.aspx
That's how it looks like in my Silverlight code:
public static class MySerializer
{
public static string Serialize<T>(T data)
{
using (var memoryStream = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memoryStream, data);
memoryStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(memoryStream);
string content = reader.ReadToEnd();
return content;
}
}
public static T Deserialize<T>(string xml)
{
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))
{
var serializer = new DataContractSerializer(typeof(T));
T theObject = (T)serializer.ReadObject(stream);
return theObject;
}
}
}
I've found the SharpSerializer package very easy to use for fast binary serlization in Silverlight: http://www.sharpserializer.com/en/index.html
Does anyone know an easy way to import a raw, XML RSS feed into C#? Am looking for an easy way to get the XML as a string so I can parse it with a Regex.
Thanks,
-Greg
This should be enough to get you going...
using System.Net
WebClient wc = new WebClient();
Stream st = wc.OpenRead(“http://example.com/feed.rss”);
using (StreamReader sr = new StreamReader(st)) {
string rss = sr.ReadToEnd();
}
If you're on .NET 3.5 you now got built-in support for syndication feeds (RSS and ATOM). Check out this MSDN Magazine Article for a good introduction.
If you really want to parse the string using regex (and parsing XML is not what regex was intended for), the easiest way to get the content is to use the WebClient class.It got a download string which is straight forward to use. Just give it the URL of your feed. Check this link for an example of how to use it.
I would load the feed into an XmlDocument and use XPATH instead of regex, like so:
XmlDocument doc = new XmlDocument();
HttpWebRequest request = WebRequest.Create(feedUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
doc.Load(reader);
<parse with XPATH>
}
What are you trying to accomplish?
I found the System.ServiceModel.Syndication classes very helpful when working with feeds.
You might want to have a look at this: http://www.codeproject.com/KB/cs/rssframework.aspx
XmlDocument (located in System.Xml, you will need to add a reference to the dll if it isn't added for you) is what you would use for getting the xml into C#. At that point, just call the InnerXml property which gives the inner Xml in string format then parse with the Regex.
The best way to grab an RSS feed as the requested string would be to use the System.Net.HttpWebRequest class. Once you've set up the HttpWebRequest's parameters (URL, etc.), call the HttpWebRequest.GetResponse() method. From there, you can get a Stream with WebResponse.GetResponseStream(). Then, you can wrap that stream in a System.IO.StreamReader, and call the StreamReader.ReadToEnd(). Voila.
The RSS is just xml and can be streamed to disk easily. Go with Darrel's example - it's all you'll need.