Json.net dynamic brackets without name [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Can you create brackets using dynamic json without the name of the list/array appearing in the json string? Otherwise I will need to rewrite entire section.
The problem is i haven't figured out how to create brackets in dymanic json without having a name that comes before it. In my json string, values will have a parent bracket wrapping all its entries, then a bracket wrapping the timestamp and another bracket wrapping the books. The brackets wrapping timestamp & books should not have names appearing in front of them.
Using this link, I got very close to the format I want but I'm missing the bracket separation for time and the remaining entries.
sample code:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
midObject.value.Add(record);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();
current output:
{
"records": [
{
"value": [
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
},
{
"Title": "Book2",
"Author": "author1"
},
{
"Title": "Book1"
"Author": "author1"
"Notes": "testtest"
}
]
}
]
}
desired output:
{
"records": [
{
"value": [
[ ------->bracket wrapping timestamp
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
}
] ------->bracket wrapping timestamp
,
[ ------->bracket wrapping books
{
"Title": "Book2",
"Artist": "artist1"
},
{
"Title": "Book1"
"Artist": "artist1"
"Notes": "testtest"
}
] ------->bracket wrapping books
]
}
]
}
edit: May have oversimplified but books section has 20+ fields. Each json string will only have one timestamp but can have 100's -1,000's of books per request.
edit2: title / clarification on the main question.

As far as I can see, you just need to add another array for all the records:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic arrayrecord = new JArray();
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
arrayrecord.Add(record);
midObject.value.Add(arrayrecord);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();

Related

How to get JSON Object using given path in string variable c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
var string = "test.data"
var json = "{'test':{'data':[{'details':{'id':'1','name':'user1'}},{'details':{'id':'2','name':'user2'}}]}}"
var output = json.string
You can try JsonPath for getting value based on path,
var json = JObject.Parse(#"{
'test':{
'data':[
{
'details':
{
'id':'1',
'name':'user1'
}
},
{
'details':
{
'id':'2',
'name':'user2'
}
}
]
}
}");
JToken data = json.SelectToken("$.test.data");
Console.WriteLine(data);
.Net Fiddle
I believe this is what you are asking for, newtonsoft json library has been used in my example.
var json = "{'test':{'data':[{'details':{'id':'1','name':'user1'}},{'details':{'id':'2','name':'user2'}}]}}";
var jObj = JObject.Parse(json);
var result = jObj.SelectToken("test.data")?.ToString();
// result
// [
// {
// "details": {
// "id": "1",
// "name": "user1"
// }
// },
// {
// "details": {
// "id": "2",
// "name": "user2"
// }
// }
// ]
To read the JSON file using its path. You can create a common method that accepts the path and you can read it.
using System;
using System.IO;
public static string ReadAllTextFromPath(string path)
{
var filePath= AppDomain.CurrentDomain.BaseDirectory + path;
var fileData = File.ReadAllText(filePath);
return fileData ;
}
If you want to convert the JSON string into an object then use the below.
var jsonString = ReadAllTextFromPath(filepath);//your JSON string
var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonString);
if you want to select a particular value from a JSON data, use the selecttoken
var object = (string)jObject.SelectToken("test.data");
//If you know "test.data" data having a structure of Model class, you can cast that class.

Ways to parse Json recursive [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My problem is that I need to parse json to another json format, I need to do that recursive. I have been tried diferents way but any works fine for me.
I would like to know more ways for test.
Thanks!
{
"items": {
"itemName": {
"type": "type",
"properties": {
"item1": {
"type": 1,
"isValid": true
},
"item2": {
"type": 1,
"isValid": true
}
}
}
}
}
And I need to make this
{
"items":{
"item1": 1,
"item2": 1
}
}
You can try with JToken to read the JSON and JsonConvert to convert the object to desired JSON
using (StreamReader r = new StreamReader(filepath))
{
var inputString = r.ReadToEnd();
JToken outer = JToken.Parse(inputString);
JObject inner = outer["items"]["itemName"]["properties"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
var items = new ExpandoObject() as IDictionary<string, Object>;
foreach (string k in keys)
{
items.Add(k, Convert.ToInt32(outer["items"]["itemName"]["properties"][k]["type"]));
}
Console.WriteLine(JsonConvert.SerializeObject(new { items = items }));
}
output
{"items":{"item1":1,"item2":2}}

Last entry in dictionary overwrites first written entry when adding dictionary to json file [duplicate]

This question already has an answer here:
Adding object to JArray overwriting first element
(1 answer)
Closed 4 years ago.
I have an existing json file which looks like this:
{
"players": [],
"games": []
}
I want to add objects to the players array so it looks like this:
{
"players": [
{
"name": "Peter",
"checksum": "6fa95b1427af77b3d769ae9cb853382f"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
Players are stored in a global Dictionary<string, string>. But in my implementation, the next element in the dictionary overwrites the first written element so when the loop is at John the next element would be Bob and then Peter gets replaced by Bob. The result of this looks like this:
{
"players": [
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
This is my code:
string json = File.ReadAllText("file.json");
JObject jsonObject = JObject.Parse(json);
JArray jsonPlayerArray = (JArray) jsonObject["players"];
JObject newPlayerEntry = new JObject();
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
string modifiedJson = jsonObject.ToString(Formatting.Indented);
File.WriteAllText("file-modified.json", modifiedJson);
(Similar questions to this have been asked several times, but I haven't been able to find a duplicate, so I figure it's worth answering instead.)
You're creating a single JObject instance, then modifying it multiple times within your loop. Each iteration will overwrite the data set in the previous iteration. Your JArray ends up with lots of references to the same JObject.
Instead, you need to create a new JObject for each entry in your dictionary. To do this, you just need to move the declaration of newPlayerEntry into the loop:
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
JObject newPlayerEntry = new JObject();
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
Now each element in the JArray will be a reference to a different JObject.

Format StreamWriter to Write/Append Json in Valid format

Good day,
How can i save/append JSON data in to the File with StreamWriter in a valid JSON format ? Is there a way to Format StreamWriter to append/write file in valid JSON format?
Like :
`[
{ "data1": "data1" },
{ "appended data2": "appended data2" },
{ "appended data3": "appended data3" },
]`
I'm using NewtonJson to serialize JSON from an object and then save it with StreamWriter.
WritableData an_data = new WritableData
{
Titel = tbTitel.Text,
Type = tbType.Text,
Episode = tbEps.Text,
Score = tbScore.Text,
Id = tbID.Text,
TitleEng = tbTitelEng.Text,
Status = tbStatus.Text,
StartDate = tbDateStart.Text,
EndDate = tbDateEnd.Text,
Image = pbImage.ImageLocation
};
string path = SavePath + "\\AnList";
string json = JsonConvert.SerializeObject(an_data, Formatting.Indented);
TextWriter tw = new StreamWriter(path + listFile, true);
tw.WriteLine(json);
tw.Close();
And it is being save as follows :
{
"Titel": "Test1",
"Type": "Movie",
"Episode": "1",
"Score": "6.92",
"Id": "894",
"TitleEng": "Test1",
"Status": "Finished Airing",
"StartDate": "1989-07-15",
"EndDate": "1989-07-15",
"Image": "https://myanimelist.cdn-dena.com/images/anime/5/10193.jpg"
}{
"Titel": "Test2",
"Type": "TV",
"Episode": "153",
"Score": "8.16",
"Id": "223",
"TitleEng": "Test2",
"Status": "Finished Airing",
"StartDate": "1986-02-26",
"EndDate": "1989-04-12",
"Image": "https://myanimelist.cdn-dena.com/images/anime/9/21055.jpg"
}
I couldn't find a way to format it right.
Thank you for your time.
You save your data to the file by appending text to the end. From what magic there'll be [ in the beginning and ] in the end? :)
Why don't you just create an array/list of objects you want to save to the file then serialize it as a whole and save text to the file?
var list = new List<WritableData>();
list.Add(an_data1);
list.Add(an_data2);
//...
list.Add(an_dataN);
var serialized = JsonConverter.SerializeObject(list);
// write to the file with 'overwrite' option, i.e. new StreamWriter(path, false/*!!!*/)
Or another approach is appending text one-by-one like you tried to do. It'll require some tricks:
create text file as [],
then every time you want to save your object (of the same type as the other previous objects), you need to:
open file and remove the last symbol ],
append ,,
append serialized object as you do in your example,
append ]
So every time you'll have a valid json of this, looked like this:
[
{...},
{...},
...
{...}
]
You want to add more properties to your an_data? So add more properties to the class.
var an_data = new WritableData() { //btw, use camelCase in var names
Prop1 = "foo",
Prop2 = "bar"
};
Or use a dictionary:
var an_data = new WritableData() {
AppendableData = new Dictionary<string, object>()
}
an_data.AppendableData["foo"] = "bar";
an_data.AppendableData["bar"] = "foo";
Ideally the serialized class (WriteableData) should contain all fields to be (de)serialized. If it doesn't and you manually append some json data then you won't be able to deserialize that appended data. If you really need to work around this and don't know what data the Json object may contain then consider using Dictionary to store some of that unknown data. But I'd advise to strongly type your serializable json object class. Otherwise you're just inviting hard to maintain code.

JSON.NET reader problem

i got some problem when i generate .json file from spring .json ,and i got this format
{ "models": [
{
"id":1,
"modelName":"dfdsf",
"created":{
"userFullname":"demo",
"time":"150301",
"date":"20110208",
"userId":"123"
},
"remark":"dsfdf",
"updated":"~unique-id~1"
},
{
"id":2,
"modelName":"test",
"created":{
"userFullname":"test",
"time":"150301",
"date":"20110210",
"userId":"124"
},
"remark":"test",
"updated":{
"userFullname":"test",
"time":"150301",
"date":"20110209",
"userId":"test"
}
}
]}
first time i used JObject Parse for convert
JObject job = JObject.Parse(fullJson);
and the other hand i used jtoken to focus "models"
JToken jDetail = job["models"];
but the problem is {[{ xxx }]} it look like jarray i don't have any idea to convert it
i ever use JArray, JsonTextReader but it doesn't work.
could suggestion some? because if i pass this ll i set some value to object.
thank you for every idea.
string fullJson = File.ReadAllText("TextFile1.txt"); // for brevity
var job = JObject.Parse(fullJson);
var models = job.Value<JArray>("models");
Console.WriteLine(models[0]);
result:
{
"id": 1,
"modelName": "dfdsf",
"created": {
"userFullname": "demo",
"time": "150301",
"date": "20110208",
"userId": "123"
},
"remark": "dsfdf",
"updated": "~unique-id~1"
}

Categories