I have used this utility http://www.convertcsv.com/csv-to-json.htm to format tables of data. It has the wonderful option of allowing you to convert to JSON or to a JSON Array. That JSON Array is what I want. When I use utilities like JSON.Net to serialize, they give me the standard JSON format. I don't want that - I just want arrays, so I can basically reproduce a table layout in my javascript.
Here is sample table data structure
column1 column2 column3
c1r1 c2r1 c3r1
c1r2 c2r2 c3r2
c1r3 c2r3 c3r3
I want it to look like this when serialized:
[[c1r1,c2r1,c3r1],
[c1r2,c2r2,c3r2],
[c1r3,c2r3,c3r3]]
But the standard serialization method with a utility like JSON.net would be
[
{
column1:c1r1,
column2:c2r1,
column3:c3r1
},
{
column1:c1r2,
column2:c2r2,
column3:c3r2
},
{
column1:c1r3,
column2:c2r3,
column3:c3r3
}
]
My question is, does anyone know of a way of stripping out column names and just making it like the simple 2d array I have shown?
Data structure is an IEnumerable taken directly from a sql command db.Query("SELECT * FROM my_table").
Note: I want to have a generic function that can do this - I know how to do this for just one thing, but the project I'm working on needs it done for many in the same way. I tried to write my own method to do it, but it didn't work because of limitations that c# has.
public static string fromListToJSONArray(IEnumerable<Object> listToUse, string[] fieldNames)
{
string JSONString = "[";
foreach (var item in listToUse)
{
JSONString += item[fieldName[0]]; //This is the line you can't do in c#!! Don't know how to go around this.
}
JSONString += "]";
return JSONString;
}
What you are trying to output is an array of arrays. Starting with an enumerable or records (in your case it looks like it has columns called column1, column2, column3).
If the query will produce a know result set you can simple convert each row to an array before converting to JSON.
var qry = /*Enumerable of some database query*/
return from rec in wry
select new string[]
{
rec.column1,
rec.column2,
rec.column3
};
I think you're asking something similar to this.
You'll have to assemble the array manually from the json.
I found the solution - IEnumerable type needed to be "dynamic". From there it is pretty simple
public static string fromListToJSONArray(IEnumerable<dynamic> listToUse)
{
string JSONString = "[";
foreach (var item in listToUse)
{
if(isFirst == false)
JSONString += ",";
else
isFirst = false;
JSONString += "\"" + item[0] + "\"";
}
JSONString += "]";
return JSONString;
JSONString += "]";
return JSONString;
}
Related
I created an ASP.NET Application, where I have to parse a csv file with a json structure.
The csv file itself is structured like:
{"Instance":"abc","Date":"2019-06-03T00:00:02.056Z","Identification":"someFunction","Type":"DurationInMs","Value":"5","iserror":"False""}
I get the jsonCsvData as a string and tried to parse it. Then I want to save some of the elements of this json object into a db.
public IActionResult ReadJsonCsvData(string jsonCsvData)
{
Console.WriteLine("ReadJsonCsvData");
ChartData chartData = new ChartData();
var lines = jsonCsvData.Split("\n");
foreach (var line in lines)
{
var values = JObject.Parse(line);
var first = string.Concat(values["Instance"]); //Output for first: ""
}
}
The problem now is, that the variable first is an empty string. The result should be (like in the json structure example above) "abc".
Thank you in advance!
I don't know if it will help but here is my solution (remove one of " at the end of your Json).
I use the "Jobject" to parse Json as I want. Import this two reference.
using Newtonsoft.Json.Linq;
using Newtonsoft;
Then you have to create your JObject :
JObject o = JObject.Parse(myJsonString);
Then to retrieve specifics data, you just have to search in your object just like you do with a dictionary with key :
instanceFromJson = o["Instance"].ToString;
dateFromJson = o["Date"].ToString;
If you have a table in your "instance" json object you can retrieve all data from this list just like that :
foreach (var item in o["Instance"]["tabFromInstanceObject"])
{
MyList.Add(item);
}
I want get data from a SQL Server database using C#. I am trying to get a json string from string builder. I try like this:
public string GetData()
{
using (SqlConnection con = new SqlConnection(this.Connection))
{
con.Open();
SqlCommand command = new SqlCommand("Select TITLE, DURATION, STATUS, TYPE from PROJECTS ", con);
StringBuilder sb = new StringBuilder();
sb.Append("{");
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var k = reader.GetString(3);
if (k == "M")
{
sb.Append("main");
sb.Append("{");
sb.Append("sub:[]");
sb.Append("Tittle:");
sb.AppendFormat("{0}", reader["TITTLE"]);
}
if (k == "S")
{
sb.Append("sub");
sb.Append("{");
sb.Append("task:[]");
sb.Append("Tittle:");
sb.AppendFormat("{0}", reader["TITTLE"]);
}
if (k == "T")
{
sb.Append("task");
sb.Append("{");
sb.Append("Tittle:");
sb.AppendFormat("{0}", reader["TITTLE"]);
}
};
}
sb.Append("}");
sb.AppendLine();
return sb.ToString();
}
}
Now I get the string like
sb = {{main{sub:[]Tittle:newsub{task:[]Tittle:new1task{Tittle:new2}
but my required string is like:
[{"main":{"sub":[{"task":[{"tittle":"new2""}],"tittle":"new1","}],"tittle":"new","}}]
means: my main title is new and sub tittle new1 and task title new2. What change do I need to do to my code to get my required json string??
There are some problems with your code:
To be a valid JSON string, property names have to be enclosed with double quotes ", so you have to do something like sb.Append("\"main\"");
Every property name has to be followed by a colon :, so you have to do something like sb.Append("\"main\": ");
You are dealing with nested structures, arrays containing objects, which themselves contain arrays ... You can only add the closing bracket ] of an array, after all its items have been added. So do something like
sb.Append("\"sub\": [");
//here you add the subitems in a loop
sb.Append("]");
To be able to do so, you will have to keep track of what structures you have open in the moment and you will have your query to return the rows in the exact required order (ie first the main titles, then the first contained sub, then the tasks contained in that sub, then the second sub, then the tasks ...)
You also never close your higher level open braces {. Same applies here as with arrays. If you add an object, you have to add all its content and then add a closing } brace.
Generally, I would suggest not to create JSON by yourself but use a framework like JSON.net. You can build up your collections as you need them and then call the frameworks serialization method which will generate a valid json string.
My code is below:
string requestBody = string.Format(
#"{{
""RequestServerVersion"":""2016.04.05"",
""PreferredDate"":""{0}"",
""StaffList"":""{1}""
}}",
preferredDate.Date.ToString("yyyy-MM-dd"),
"test");
StaffList is a string array, If I pass a single string like "test", it won't work. How do I pass a string array to it in the string.Format(...)? Since in the server side, StaffList is handled as a string Array.
Thanks a lot!
I would avoid rolling your own JSON when there are good libraries for making sure it works properly.
Try this with Newtonsoft.Json:
string[] staffList = new [] { "Alice", "Bob", "Charlie" };
DateTime preferredDate = DateTime.Now;
var data = new
{
RequestServerVersion = "2016.04.05",
PreferredDate = preferredDate.Date.ToString("yyyy-MM-dd"),
StaffList = staffList,
};
string requestBody = Newtonsoft.Json.JsonConvert.SerializeObject(data);
This outputs:
{
"RequestServerVersion":"2016.04.05",
"PreferredDate":"2016-04-05",
"StaffList":["Alice","Bob","Charlie"]
}
Two things that come into my mind:
Try to join the Array to a single string using string.Join() and split the string on serverside using string.Split()
Use the JSON Arrays Syntax in your code, Loop over each Array index and insert them one by one in this syntax: http://www.w3schools.com/json/json_syntax.asp
BTW: Have you considered to use Serialization instead of building your JSON on your own?
Im trying to find an answer for this but i must be searching for the wrong terms.
Im working on a Windows phone app and am getting data from an API with a nested array value "user.username"
void data_arrived(object sender, DownloadCompleteData e)
{
String data = e.data;
JArray obj = JArray.Parse(data);
for (int i = 0; i < obj.Count; i++)
{
JObject row = JObject.Parse(obj[i].ToString());
var item = new DataList();
item.country = row["title"].ToString() + " (€" + row["price"].ToString() + ") ";
item.code = row["price"].ToString();
item.imageURL = row["urlimage"].ToString();
item.votes = row["votes"].ToString();
item.category = row["category"].ToString();
item.username = row["user.username"].ToString();
list.Items.Add(item);
}
}
Everything else works fine except user.username
How do i use this properly?
Thanks
You can deserialize a valid JSON string to a dynamic object. This will allow you access to underlying object using dot notation. e.g.
dynamic row = JsonConvert.DeserializeObject (obj[i].ToString());
Your final code block inside loop will look like
dynamic row = JsonConvert.DeserializeObject(obj[i].ToString());
Console.WriteLine(row.title.ToString() + " (€" + row.price.ToString() + ") ");
Console.WriteLine(row.price.ToString());
Console.WriteLine(row.urlimage.ToString());
Console.WriteLine(row.votes.ToString());
Console.WriteLine(row.category.ToString());
Console.WriteLine(row.user.username.ToString());
Console.WriteLine();
Console.WriteLine("-----------------------------\n");
There is no "easy" way to achieve this because the . in C# is reserved.
However, you could achieve something pretty close by using a dictionary and collection initializer. It's still somewhat isolated, and doesn't require you to create a custom class.
var obj = new Dictionary<string, object>
{
{ "user.username", "myvalue" }
};
var json = JsonConvert.SerializeObject(obj);
//{"user.username":"myvalue"}
I'm trying to automate the addition of new objects to an existing JSON file. I looked all around the web but only found adding data and stuff but not a whole object. This is how the file that I want to edit looks:
[
{"id":"123","name":"carl"}
]
and I want to go to
[
{"id":"123","name":"carl"},
{"id":"1234","name":"carl2"}
]
Thank you for all your answers but I don't think everyone completely understands what i mean I have tried some of the answers but then I get this:
[
"{\"id\":\"123\",\"name\":\"carl\"}"
]"{\"id\":\"1234\",\"name\":\"carl2\"}"
and I want everything in between the [].
If you use json.NET you can simply deserialize and serialize the json.
var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
Using Json.Net
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
var array = JArray.Parse(initialJson);
var itemToAdd = new JObject();
itemToAdd["id"] = 1234;
itemToAdd["name"] = "carl2";
array.Add(itemToAdd);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
//save to file here
Using this method doesn't require strongly typed objects
You could replace this bit:
//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
With
var initialJson = File.ReadAllText(#"c:\myjson.json")
To load the json from a text file
A better performing solution than serializing/deserializing what may be a large file would be to open a FileStream, seek 1 character before the end, then serialize and write your new object into the array, then write a closing bracket. See this question C# How to delete last 2 characters from text file and write into the same line at the end my text?, I'll copy the code here - you already know how to serialize your object and encode it into bytes.
using(var fs = new FileStream("file.json")) {
fs.Seek(-1,SeekOrigin.End);
fs.Write(mySerializedJSONObjAsBytes,0,mySerializedJSONObjAsBytes.Length); // include a leading comma character if required
fs.Write(squareBracketByte, 0, 1);
fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
}
Sorry haven't tested any of that, it's off the top of my head. Pro-tip: wrap FileStream in a StreamWriter so can write strings directly.
You could create a method:
public string AddObjectsToJson<T>(string json, List<T> objects)
{
List<T> list = JsonConvert.DeserializeObject<List<T>>(json);
list.AddRange(objects);
return JsonConvert.SerializeObject(list);
}
Then use it like this:
string baseJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
List<Person> personsToAdd = new List<Person>() { new Person(1234,"carl2") };
string updatedJson = AddObjectsToJson(baseJson, personsToAdd);
this would be a sample for you:
var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.id="1";
list.Add(example);
string output = JsonConvert.SerializeObject(list);
public class Example
{
public string id {get;set;}
public string name { get; set; }
}
I have been looking for a solution to this exact question for a week now. I finally figured out how to append it to the existing json array and not add it as a solo object after the array. Make sure you are using WriteAllText and not AppendAllText. Here is what I did:
JArray array = JsonConvert.DeserializeObject<JArray (jsonFile);
JObject obj = new JObject();
obj.Add("ID", "123");
obj.Add("Name", "Brian");
array.Add(obj);
var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
File.WriteAllText("fileName.json", jsonToOutput);