Convert Byte Array into List Windows phone 8 - windows-phone-8

I am using this piece of code to convert List into byte array but again I want to convert to this data into List how it is possible.
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();

In your example it isn't possible, because you have no way to tell where a string ends and where the next one starts. It would be possible by using a separator (the character \0 is often used to indicate the end of a string):
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + '\0').ToArray();
You can then retrieve your list by using the Split method:
var stringList = System.Text.Encoding.UTF8.GetString(byteArr, 0, byteArr.Length).Split('\0');
But overall I don't think it's a good idea. Depending on what you need, I'd rather recommend to use the DataContractSerializer to convert your array to bytes:
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<string>));
byte[] byteArr;
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, stringlist);
byteArr = ms.ToArray();
}
And to convert it back:
using (var ms = new System.IO.MemoryStream(byteArr))
{
stringlist = (Sserializer.ReadObject(ms);
}

Related

Visual C# Cannot get CSV file to load into a 2D array

I have a very simple .csv file with ID's and serial numbers
the actual application will not know how many rows but will always have two columns
1,16600687
2,16600939
3,16604031
4,16607302
I have everything else setup but i am only loading the data into a 1D array and the comma is remaining in the data
The result i get is string value for 3rd position is 3,16604031
How do i separate this so it is a 2D array with get value [2,0] is 3 and get value [2,1] is 16604031 ?
private void button1_Click(object sender, EventArgs e)
{
string stFileNamenPath = "(put location of file here)";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
string stTest = (string)sortArray.GetValue(2);
MessageBox.Show("string value for 3rd position is " + stTest);
}
CSV file
1,16600687
2,16600939
3,16604031
4,16607302
The answer that comes to my mind is just a LINQ Where statement followed by a Select statement. The former for filtering and the second for actually remaping the data you have. You code would be something like this
string stFileNamenPath = "(put location of file here)";
//DialogResult result = openFileDialog1.ShowDialog();
StreamReader sr = new StreamReader(stFileNamenPath);
string[] sortArray = null;
while (!sr.EndOfStream)
{
string strResult = sr.ReadToEnd();
sortArray = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
char separator = ',';
var mappedArray = sortArray
.Where(x => !string.IsNullOrEmpty(x) && !string.IsNullOrWhiteSpace(x))
.Select(x => new string[] { x.Split(separator)[0], x.Split(separator)[1] }).ToArray();
var stTest = mappedArray[2][1];
MessageBox.Show("string value for 3rd position is " + stTest);

Is it possible to use JsonReaderWriterFactory to convert XML to JSON without using DataContractJsonSerializer?

I need a generic routine that takes any valid XML and converts it to JSON without knowing the underlying data type. I know that this is easily done with Json.Net and I also know how to do it with the DataContractJsonSerializer but our organisation doesn't use Json.Net and the DataContractJsonSerializer needs a Data Contract enabled object type.
My working code using Json.Net:
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(document);
The code I'd like to be able to use, using JsonReaderWriterFactory instead of Json.Net:
string jsonText = string.Empty;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.Write(xml);
streamWriter.Flush();
stream.Position = 0;
using (XmlDictionaryWriter xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(stream))
{
object someObject = new object();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(someObject.GetType());
serializer.WriteObject(stream, someObject);
xmlWriter.Flush();
jsonText = Encoding.Default.GetString(stream.GetBuffer());
}
Is there a way around this?
Too bad the Json.Net isn't an option - we've used it for years now, and it's fantastic. Short of native parsing and json generation by hand, there's not a lot of fast ways to do this.
Check out the code from this link:
http://www.phdcc.com/xml2json.htm (See section "XmlToJSON C# code", should be fairly quick)
This code could easily be adapted to a class or even extension to convert an XML Document (or even just xml string being parsed into an XML document, then returning the json.
Another approach to consider could be the following. It specifies using anonymous types assuming you don't have control of the objects that could be deserialized from XML (and you don't want to manage those separate types).
Convert the XML into an anonymous type (probably through the
Use the JavascriptSerializer to serialize the anonymous object into the json
The code sample below shows this techinique:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;
namespace Scratch
{
class Program
{
static void Main(string[] args)
{
string xml = "<root><student><id>1</id></student><student><id>2</id></student></root>";
string json = XmlToJson(xml);
Console.WriteLine(json);
Console.ReadKey(true);
}
// Using JavaScriptSerializer
static string XmlToJson(string xml)
{
var obj = GetAnonymousType(xml);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(obj);
}
// Adapted from: http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO
static dynamic GetAnonymousType(string xml, XElement node = null)
{
node = string.IsNullOrEmpty(xml) ? node : XDocument.Parse(xml).Root;
IDictionary<String, dynamic> result = new ExpandoObject();
var pluralizationService = PluralizationService.CreateService(CultureInfo.CreateSpecificCulture("en-us"));
node.Elements().AsParallel().ForAll(gn =>
{
var isCollection = gn.HasElements
&& (gn.Elements().Count() > 1
&& gn.Elements().All(e => e.Name.LocalName.ToLower() == gn.Elements().First().Name.LocalName)
|| gn.Name.LocalName.ToLower() == pluralizationService.Pluralize(gn.Elements().First().Name.LocalName).ToLower());
var items = isCollection ? gn.Elements().ToList() : new List<XElement>() { gn };
var values = new List<dynamic>();
items.AsParallel().ForAll(i => values.Add((i.HasElements) ? GetAnonymousType(null, i) : i.Value.Trim()));
result[gn.Name.LocalName] = isCollection ? values : values.FirstOrDefault();
});
return result;
}
}
}

Error generating a list with REST to produce JSON response

I'm trying to consume a list with Json from Android. But, I think that I'm not generating well the list, and when I try to parse with Json I get and error.
I'm getting this result:
[{"id":7,"word":"w6","definition":"d6","language":"es","numberDefinition":0,"success":false},{"id":8,"word":"w7\n","definition":"d7","language":"es","numberDefinition":0,"success":false},{"id":9,"word":"w8","definition":"d8","language":"es","numberDefinition":0,"success":false}]
#GET
#Path("words")
#Produces(MediaType.APPLICATION_JSON)
public List<Word> getWords(#QueryParam("number") int number ) {
List<Word> list = null;
list = dictionary.getListWords(number);
return list;
}
My java codein Android is:
respJSON = new JSONObject(response);
JSONArray lineItems = respJSON.getJSONArray("words");
listWords = new ArrayList<Word>();
for(int i=0; i<lineItems.length(); i++)
{
JSONObject obj = lineItems.getJSONObject(i);
id = obj.getInt(ConstantsTrivial.WORD_ID);
definition = obj.getString(ConstantsTrivial.WORD_DEFINITION);
language = obj.getString(ConstantsTrivial.WORD_LANGUAGE);
wordName = obj.getString(ConstantsTrivial.WORD_NAME);
numberDefinition = obj.getInt(ConstantsTrivial.WORD_NUMBER_DEFINITION);
word = new Word(id, wordName, definition, language, numberDefinition);
listWords.add(word);
}
I'm looking for a "words",, I know this mistake, but I dont know what I should do so that my webservice generate the list on the right way..
The error is:
03-19 13:09:48.086: E/WebServiceTask(9868): Value [{"numberDefinition":0,"id":1,"word":"w0","language":"ES","definition":"d0","success":false},{"numberDefinition":0,"id":3,"word":"w2","language":"es","definition":"d2","success":false},{"numberDefinition":0,"id":4,"word":"w3","language":"es","definition":"d3","success":false},{"numberDefinition":0,"id":9,"word":"w8","language":"es","definition":"d8","success":false}] of type org.json.JSONArray cannot be converted to JSONObject
Thank you.
The error is in the first line of your code. Your value is a JSONArray, not a JSONObject. The line should be:
JSONArray lineItems = new JSONArray(response);
And don't forget to delete the second line.

Is there any Checksum like mechanism for JSON?

I need to upload large amount of JSON data to a webservice. Whats the best way to analyse that the server received the data correctly and all data is uploaded? Please let me know if anyone has any experience in this regards. Thanks.
You can check out my project :
https://github.com/hidayetcolkusu?tab=repositories
Calculation:
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU""}";
ushort checksum = checksumCalculator.Calculate(json);
Result: 43460
Comparing:
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU""}";
bool result = checksumCalculator.Compare(json, 43460);
Resut:true
Or
ChecksumCalculator checksumCalculator = new ChecksumCalculator();
string json = #"{""Name"":""Hidayet Raşit"",""Surname"":""ÇÖLKUŞU"",""Checksum"":43460}";
bool result = checksumCalculator.Compare(json);
Result:true
You can calculate json's hash value like this:
var sha1 = System.Security.Cryptography.SHA1.Create();
byte[] buf = System.Text.Encoding.UTF8.GetBytes(jsonString);
byte[] hash= sha1.ComputeHash(buf, 0, buf.Length);
var hashstr = System.BitConverter.ToString(hash).Replace("-", "");
You can calculate md5 to compare two json.
public static string CreateMD5(string json)
{
// Use json string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(json);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}

how to Convert string into Json using Newton Json library

sorry for the silly question, but i am stuck converting for example the following result from a method into Json
public string Test(string input) {
return "Name:" + input;
}
to look like this
{"Name":"Mike"}
Update:
Darin fixed first problem now i am using this way but it is not working
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using(JsonWriter jsonWriter = new JsonTextWriter(sw)) {
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Mike");
}
I get
'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}';
You could use the JavaScriptSerializer class:
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
Example usage:
string json = Test("Mike"); // json = {"Name":"Mike"}
UPDATE:
Didn't notice you wanted a solution using the Json.NET library. Here's one:
string json = JsonConvert.SerializeObject(new { Name = input });