I am creating an app that gets information and download movies from a site. I have succeeded in setting the information in different arrays and combining them together to 1 array.
However, now I am trying to put that array inside a bigger array (want to work with JSON), and that is failing.
My current Json output looks like this:
{"moviedata":
["http:/xxxx","title title ","k0X0HrYtMm5u"],"tags":
["x","x","x","Prop","x","x","x","x","x","x","x"],"categorydata":
["x","x","x"]}
Which is achieved with this code:
Dictionary<string, string[]> movie = new Dictionary<string, string[]>();
moviedata.Add("moviedata", moviegenerala);
moviedata.Add("tags", tagsa);
moviedata.Add("categorydata", categoriesa);
string moviejson = JsonConvert.SerializeObject(moviedata);
I want to add another layer on top of this, so there is a general tab named "Movie", and for each movie it has this information. How would I do that?
UPDATE:
Added this code:
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
The JSON seems to be correct, but it cannot parse, after the first listing it says there is text after the closing bracket.
UPDATE:
Changed code to this:
Dictionary<string, string[]> movies = new Dictionary<string, string[]>();
var myShape = movies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa,
["localdata"] = localdataa
}
});
var moviejson = JsonConvert.SerializeObject(myShape);
File.AppendAllText("moviedata.txt", moviejson);
But now it only gives empty brackets :(
If this is a one-off serialization, then simplest could be just to wrap the Dictionary with an anonymous class adding the extra property indentation, e.g.
var myShape = new
{
Movie = new Dictionary<string, string[]>
{
["moviedata"] = moviegenerala,
["tags"] = tagsa,
["categorydata"] = categoriesa
}
};
var moviejson = JsonConvert.SerializeObject(myShape);
However, if this same shape is required in multiple places in your code, then I would recommend that you create a fully fledged class for your 'Shape'.
Edit:
The json produced by the above is
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
If you need to map multiple Movies, then project then you can use a .Select:
// TODO : Replace this with your actual current movies
var inMovies = new[] {new Movie{...},new Movie {...}, ...};
var myShape = inMovies.Select(m => new
{
Movie = new Dictionary<string, string[]>
{
// TODO - you'll need to get the appropriate data for this movie, e.g. m.moviegenerala
["moviedata"] = moviegenerala,
...
}
});
Produces the following:
[
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
},
{
"Movie": {
"moviedata": [ "http:/xxxx", "title title ", "k0X0HrYtMm5u" ],
"tags": [ "x", "x", "x", "Prop", "x", "x", "x", "x", "x", "x", "x" ],
"categorydata": [ "x", "x", "x" ]
}
}
]
Related
I have a list of two dimensions dynamic as follows :
List<dynamic> tableContent = new List<dynamic>();
List<dynamic> rowHeader = new List<dynamic>();
rowHeader.add("First header");
rowHeader.add("Second header");
rowHeader.add("Third header");
tableContent.add(rowHeader);
for (int i = 0; i < 5; i++) {
List<dynamic> rowContent = new List<dynamic>();
rowContent.add("1");
rowContent.add("2");
rowContent.add("3");
tableContent.add(rowContent);
}
My tableContent is essentially
"First header", "Second header", "Third header"
"1" , "2" , "3"
"1" , "2" , "3"
"1" , "2" , "3"
"1" , "2" , "3"
"1" , "2" , "3"
I want to transform it into json as
[{"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}
, {"First header":"1","Second header":"2","Third header":"3"}]
How do I do this without changing my initial for loop to create my tableContent? (since I also need it for doing something else).
Thank you
Eko
Your tableContent is not essential to your example. Your tableContent right now is a List<List<string>> so it will be serialized as
[["First header","Second header","Third header"],["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"]]
If you need to keep your for loop unchanged, then write your own custom serializer. If you have no need in keeping for loop unchanged, form your data in right way. For an example:
var tableContent = new List<dynamic>();
for (int i = 0; i < 5; i++)
{
var rowContent = new Dictionary<dynamic, dynamic>();
rowContent["First header"] = "1";
rowContent["Second header"] = "2";
rowContent["Third header"] = "3";
tableContent.Add(rowContent);
}
Will result as:
[{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"},{"First header":"1","Second header":"2","Third header":"3"}]
P.S. if you have no special purposes, you can change your dynamic to strong types:
var tableContent = new List<Dictionary<string, string>>();
for (int i = 0; i < 5; i++)
{
var rowContent = new Dictionary<string, string>();
rowContent["First header"] = "1";
rowContent["Second header"] = "2";
rowContent["Third header"] = "3";
tableContent.Add(rowContent);
}
You can use newtonsoft - Json.NET to build (and parse) jsons.
It can be used in various ways, both "manually" and using automatic serialization. See here: Creating JSON.
The code below demonstrates how to use the "manual" approach to build the json in parallel to building your current data structure (like I understood you'd like to do):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
namespace Test
{
internal class Program
{
static void Main(string[] args)
{
List<List<string>> tableContent = new List<List<string>>();
JArray tableJson = new JArray(); // This will be the table json object we will build
string[] headerNames = { "First header", "Second header", "Third header" };
List<string> rowHeader = new List<string>();
rowHeader.Add(headerNames[0]);
rowHeader.Add(headerNames[1]);
rowHeader.Add(headerNames[2]);
tableContent.Add(rowHeader);
for (int i = 0; i < 5; i++)
{
List<string> rowContent = new List<string>();
JObject rowJson = new JObject(); // This will be the json for one row
string[] rowElements = { "1", "2", "3" };
Debug.Assert(rowElements.Length == headerNames.Length);
for (int j = 0; j < rowElements.Length; ++j)
{
rowContent.Add(rowElements[j]);
rowJson[headerNames[j]] = rowElements[j]; // Add the element to the row json
}
tableContent.Add(rowContent);
tableJson.Add(rowJson); // Add the row json to the table json
}
// Here tableJson contains the required json.
// Convert to string and print:
string tableJsonString = tableJson.ToString();
Console.WriteLine(tableJsonString);
}
}
}
Output:
[
{
"First header": "1",
"Second header": "2",
"Third header": "3"
},
{
"First header": "1",
"Second header": "2",
"Third header": "3"
},
{
"First header": "1",
"Second header": "2",
"Third header": "3"
},
{
"First header": "1",
"Second header": "2",
"Third header": "3"
},
{
"First header": "1",
"Second header": "2",
"Third header": "3"
}
]
Note: I changed the dynamic lists to have concrete types as this is more efficient.
So full disclousre this is homework. Anyway trying to make a morse code converter and I am just stuck on this last issue. I want to use chars and then use string.replace but I can't since my dictionary is all strings. I want to use chars though. So how would I get around this?
public void InputReader()
{
string inputForTranslating = inputForTranslator.Text;
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "A", ".-" },
{ "B", "-..." }, { "C", "-.-." }, { "D", "-.." }, { "E", "." }, { "F", "..-." }, { "G", "--." }, { "H", "...." }, { "I", ".." },
{ "J", ".---" }, { "K", "-.-" }, { "L", ".-.." }, { "M", "---" }, { "N", "-." }, { "O", "---" }, { "P", ".--." }, { "Q", "--.-" },
{ "R", ".-." }, { "S", "..." }, { "T", "-" }, { "U", "..-" }, { "V", "...-" }, { "W", ".--" }, { "X", "-..-" }, { "Y", "-.--" },
{ "Z", "--.." }
};
char[] charArray = inputForTranslating.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
outPutTranslation.Text = outPutTranslation.ToString().Replace(morseDictionary.Keys, morseDictionary.Values); ////This is where the error occurs "cannot convert from 'System.Collections.Generic.Dictionary<string, string>.KeyCollection' to 'char'"
}
}
Replace takes strings/chars as parameters, not a collection of keys or values.
In this case, you don't even need the Replace, you can just add the values based on the keys.
Also, your outPutTranslation.Text will only have the last char.
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "A", ".-" },
{ "B", "-..." }, { "C", "-.-." }, { "D", "-.." }, { "E", "." }, { "F", "..-." }, { "G", "--." }, { "H", "...." }, { "I", ".." },
{ "J", ".---" }, { "K", "-.-" }, { "L", ".-.." }, { "M", "---" }, { "N", "-." }, { "O", "---" }, { "P", ".--." }, { "Q", "--.-" },
{ "R", ".-." }, { "S", "..." }, { "T", "-" }, { "U", "..-" }, { "V", "...-" }, { "W", ".--" }, { "X", "-..-" }, { "Y", "-.--" },
{ "Z", "--.." }
};
string output = "";
foreach (char c in inputForTranslating.ToCharArray())
{
output += morseDictionary[c];
}
outPutTranslation.Text = output;
Well, string.Replace() works both with two chars or two strings. The error clearly states that morseDictionary.Keys is not a string. Neither is morseDictionary.Values. And it's right, they are the list of keys and values of the dictionary!
There's another mistake in that code. You're converting your input to a char array, and then iterating each character, and trying to replace there. Think about what it's doing:
If you have -.-, in the first iteration you will search over -, in the second over . and lastly over -. You'll never be able to find the K.
You should iterate your dictionary, and search each word in the whole string.
foreach(string key in morseDictionary) {
//for morse->letter
inputForTranslating=inputForTranslating.Replace(morseDictionary[key],key);
//for letter->morse
inputForTranslating=inputForTranslating.Replace(key,morseDictionary[key]);
I have two lists of string:
List<string> tmpCols = new List<string>();
List<string> tmpRows = new List<string>();
e.g. tmpCols = [A,B,C]; and tmpRows = [X, Y];
I need to iterate both list and get a Json result like this:
new matrix() { id = "1", col = "A", row = "X" });
new matrix() { id = "2", col = "B", row = "X" });
new matrix() { id = "3", col = "C", row = "X" });
new matrix() { id = "4", col = "A", row = "Y" });
new matrix() { id = "5", col = "B", row = "Y" });
new matrix() { id = "6", col = "C", row = "Y" });
The dimension in this case would be 2 rows and 3 columns.
This is a textbook example of a nested loop. Loops can contain other loops, where the inner one repeats for each element of the outer one. This one might look something like:
var result = new List<matrix>();
var count = 1;
foreach (var r in tmpRows)
foreach (var c in tmpCols)
result.Add(new matrix { id = (count++).ToString(), col = c, row = r });
I think this is a late answer
need to iterate both list and get a Json result like this:
It is not a json, I guess you want something like this
List<string> tmpCols = new List<string>() { "A", "B", "C" };
List<string> tmpRows = new List<string>() { "X", "Y" };
var query = tmpCols.SelectMany(c => tmpRows.Select(r => new {id=index++, col=c, row = r }));
var json = JsonConvert.SerializeObject(query, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
OUTPUT:
[
{
"id": 6,
"col": "A",
"row": "X"
},
{
"id": 7,
"col": "A",
"row": "Y"
},
{
"id": 8,
"col": "B",
"row": "X"
},
{
"id": 9,
"col": "B",
"row": "Y"
},
{
"id": 10,
"col": "C",
"row": "X"
},
{
"id": 11,
"col": "C",
"row": "Y"
}
]
Solved using this code:
var tmpMatrix = new List<matrix>();
for (int k = 0; k < tmpRows.Count; k++)
{
for (int j = 0; j < tmpCols.Count; j++)
{
int ident = k*tmpCols.Count + j;
tmpMatrix.Add(new matrix() { id = ident.ToString(), col = tmpCols[j], row = tmpRows[k] });
}
}
What is the best way to compare two lists based on values, order and the number of values. So all of the lists below should be different.
var list1 = new List<string> { "1", "2" };
var list2 = new List<string> { "2", "1" };
var list3 = new List<string> { "1", "2", "3" };
How about using SequenceEqual.
See http://ideone.com/yZeYRh
var a = new [] { "1", "2", "3" };
var b = new [] { "1", "2" };
var c = new [] { "2", "1" };
Console.WriteLine(a.SequenceEqual(b)); // false
Console.WriteLine(a.SequenceEqual(c)); // false
Console.WriteLine(c.SequenceEqual(b)); // false
It comes from the namespace System.Linq and can be used on any IEnumerable.
You can also pass it an IEqualityComparer to for example also do:
var d = new [] { "a", "B" };
var e = new [] { "A", "b" };
Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
I like Zip for this, but you still need to manually compare Count.
lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);
I am using C# regex library to do some text find and replace.
I would like to change the following:
1 -> one
11 -> one one
123 -> one two three
for example, here's my code to replace ampersand:
string pattern = "[&]";
string replacement = " and ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(text, replacement);
Edit
I found some great examples of .NET RegEx on MSDN:
http://msdn.microsoft.com/en-us/library/kweb790z.aspx
Since you're specifically asking for a regex, you could do something like this
var digits = new Dictionary<string, string> {
{ "0", "zero" },
{ "1", "one" },
{ "2", "two" },
{ "3", "three" },
{ "4", "four" },
{ "5", "five" },
{ "6", "six" },
{ "7", "seven" },
{ "8", "eight" },
{ "9", "nine" }
};
var text = "this is a text with some numbers like 123 and 456";
text = Regex.Replace(text, #"\d", x => digits[x.Value]);
which will give you
this is a text with some numbers like onetwothree and fourfivesix