how to insert a data in json text file - c#

I need to insert a new piece of data in a text file.
This is the method I use to read the text file:
try
{
var path = #"text file\\GetAllEmp.txt";
string rawJson = File.ReadAllText(path, Encoding.UTF8);
ObservableCollection<EmployeeItem> Employee = new ObservableCollection<EmployeeItem>();
var jsonData = JsonConvert.SerializeObject(rawJson);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
listitem.ItemsSource = emp;
I just need to add new data in the text file.
How to add data?
What I have tried is:
public static void Writeemployee()
{
var path = #"text file\\GetAllEmp.txt";
string rawJson = File.ReadAllText(path);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
var abs = emp;
for (int i = 0; i < abs.Count; i++)
{
EmployeeItem s_Item = new EmployeeItem();
int SID = ((int)s_Item.SiteID);
DataAccess.AddEmployee(s_Item);
}
}
My data access:
public static async void AddEmployeee(EmployeeItem Employee)
{
}
I just don't know how to insert. If there is any other method to insert, please let me know.

Using the file APIs in UWP cannot add items to the Json file without deleting the original items.
Because of the format of the Json file, items need to be placed in [{items1},{items2 }], so you need to read all the items, then add new elements, convert the list to Json format and write it to the file.
Here is a code sample.
EmployeeItem employeeItem = new EmployeeItem
{
Id = 8,
GroupID = 18,
SiteID = 5565
};
StorageFolder appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
string path = #"GetAllEmp.txt";
//get data
string rawJson = File.ReadAllText(path, Encoding.UTF8);
ObservableCollection<EmployeeItem> Employee = new ObservableCollection<EmployeeItem>();
var jsonData = JsonConvert.SerializeObject(rawJson);
List<EmployeeItem> emp = JsonConvert.DeserializeObject<List<EmployeeItem>>(rawJson);
emp.Add(employeeItem);
StorageFile sampleFile = await appFolder.GetFileAsync(path);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, JsonConvert.SerializeObject(emp));

Related

c# .netcore Get ImageURL of all files under amazon s3 folder

Using C# and amazon .Net core, able to list all the files URL path with in a amazon S3 folder as below:
public async Task<string> GetMenuUrl(entities.Restaurant restaurant)
{
AmazonS3Client s3Client = new AmazonS3Client(_appSettings.AWSPublicKey, _appSettings.AWSPrivateKey, Amazon.RegionEndpoint.APSoutheast2);
string imagePath;
int restaurantId = restaurant.RestaurantId;
ListObjectsRequest listRequest = new ListObjectsRequest();
ListObjectsResponse listResponse;
imagePath = $"Business_menu/{restaurantId}/";
listRequest.BucketName = _appSettings.AWSS3BucketName;
listRequest.Prefix = imagePath;
do
{
listResponse = await s3Client.ListObjectsAsync(listRequest);
} while (listResponse.IsTruncated);
var files = listResponse.S3Objects.Select(x => x.Key);
var fileName = files.Select(x => Path.GetFileName(x)).ToList(); //outputs Test.jpg, Test2.jpg on this line
var fileNameJoin = string.Join(", ", fileName);
var result = fileNameJoin.Split(); // contains 2 files Test.jpg, Test2.jpg
//Need AWSS3BucketUrl for all files in imagePath
string imageUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{result}";
return imageUrl;
}
public async Task<MenuResponse> GetVenueMenuUrl(int restaurantId)
{
var restaurant = await _context.Restaurant.Where(w => w.RestaurantId == restaurantId).FirstOrDefaultAsync();
var result = await _Service.GetMenuUrl(restaurant);
var response = new MenuResponse()
{
MenuUrl = result
};
return response;
}
I want to return each imageurl as the following:
{
menuUrl : "https://...bucketpath../test.jpg"
},
{
menuUrl: "https://...bucketpath../test2.jpg"
},
What Is currently being outputted:
{
"menuUrl": "https://..bucketpath../System.String[]"
}
It should be outputting two imageUrls not one and also it seems to be outputting the list type not the content.
string imageUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{result}";
You're telling C# to concatenate a string with "result", but "result" is not a string, it's an array. To tell the compiler what you really want, you need to get the individual strings out of the array and use those instead.
It also looks like you're converting your result into JSON in code we can't see. If that's the case, you could try returning a list of objects from your function instead of a string, which will then get serialized into something a lot closer to your expected output:
// make a simple class that will be serialized cleanly
public class MenuURL
{
public string menuUrl;
}
// .... back in your function ....
List<MenuURL> URLs = new List<MenuURL>();
// Loop through your "results" variable
foreach (string str in result)
{
MenuURL url = new MenuURL()
{
menuUrl = $"{_appSettings.AWSS3BucketUrl}{imagePath}{str}"
};
URLs.Add(url);
}
return URLs;
When you convert the list you get back into JSON, it should look more like what you want, ie:
[
{
"menuUrl" : "https://...bucketpath../test.jpg"
},
{
"menuUrl": "https://...bucketpath../test2.jpg"
},
]

How do you run through the entire JSON file, while filtering out specific values & strings from code behind?

may i know how do you run through the entire JSON file and during the process, filter out specific values and strings, such as db_table_name? from code - behind
Here is an example of a JSON file
d={"db_table_name":"form_for_hub_trooper_in_store_feedback_form_20160829174321","Date of Audit":"2017-04-27"}
test.json file:
{
"db_table_name": "from_for_bub_trooper_in_store_feedback_from_20160829174321",
"Date of Audit": "2017-04-27"
}
You may simply use Newtonsoft.Json. Working code is below:
string jsonText = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.json");
using (StreamReader r = new StreamReader(jsonText))
{
string json = r.ReadToEnd();
JObject token = JObject.Parse(json);
string dbTable = token.SelectToken("db_table_name").ToString();
}
If you want to access json dynamically by condition:
string jsonText = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.json");
using (StreamReader r = new StreamReader(jsonText))
{
string json = r.ReadToEnd();
dynamic dynamicJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynamicJson)
{
if (item.Name == "db_table_name")
Console.WriteLine(item.Value);
if (item.Name == "Date of Audit")
Console.WriteLine(item.Value);
}
}
void Main()
{
string d = "{'db_table_name':'form_for_hub_trooper_in_store_feedback_form_20160829174321','Date of Audit':'2017-04-27'}";
var obj = (JObject)JsonConvert.DeserializeObject(d);
Console.WriteLine($"Table Name = {(obj["db_table_name"])}");
}

Trouble Fetching Value in Variable

Basically here's my code which I'm having trouble with. Insanely new to mongoDB and would love to understand how to get values out of a JSON string that is returns in the variable 'line'.
public string get_data()
{
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var cursor = collection.Find("{'movie_name' : 'Hemin'}").ToCursor();
var line = "";
foreach (var document in cursor.ToEnumerable())
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
line = stringWriter.ToString();
}
}
var js = new JavaScriptSerializer();
var d = js.Deserialize<dynamic>(line);
var a = d["movie_name"];
return line;
}
This is the output I get if I return line:
{ "_id" : ObjectId("58746dcafead398e4d7233f5"), "movie_name" : "Hemin"
}
I want to be able to fetch the value 'Hemin' into 'a'.
I know this is not what you're asking for but since you're using the c# driver then I would recommend the following. Assumes you have a c# class corresponding to metacorp collection or at least a serializer that handles it. Hope it helps.
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<MetaCorp>("metacorp");
var m = collection.SingleOrDefault(x => x.Movie_Name == "Hemin"); // Assuming 0 or 1 with that name. Use Where otherwise
var movieName = "Not found";
if(m!= null)
movieName = m.Movie_Name;
You could have your dto class for movie ans just fetch the data from collection:
public class Movie
{
public ObjectId Id { get; set; }
public string movie_name { get; set;}
}
...
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var movies = collection.Find(x=>x.movie_name == "Hemin").ToEnumerable();

Inserting json documents in DocumentDB

In DocumentDB documentation examples, I find insertion of C# objects.
// Create the Andersen family document.
Family AndersenFamily = new Family
{
Id = "AndersenFamily",
LastName = "Andersen",
Parents = new Parent[] {
new Parent { FirstName = "Thomas" },
new Parent { FirstName = "Mary Kay"}
},
IsRegistered = true
};
await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersenFamily);
In my case, I'm receiving json strings from application client and would like to insert them in DocumentDB without deserializing them. Could not find any examples of doing something similar.
Any help is sincerely appreciated..
Thanks
Copied from the published .NET Sample code -
private static async Task UseStreams(string colSelfLink)
{
var dir = new DirectoryInfo(#".\Data");
var files = dir.EnumerateFiles("*.json");
foreach (var file in files)
{
using (var fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
{
Document doc = await client.CreateDocumentAsync(colSelfLink, Resource.LoadFrom<Document>(fileStream));
Console.WriteLine("Created Document: ", doc);
}
}
//Read one the documents created above directly in to a Json string
Document readDoc = client.CreateDocumentQuery(colSelfLink).Where(d => d.Id == "JSON1").AsEnumerable().First();
string content = JsonConvert.SerializeObject(readDoc);
//Update a document with some Json text,
//Here we're replacing a previously created document with some new text and even introudcing a new Property, Status=Cancelled
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("{\"id\": \"JSON1\",\"PurchaseOrderNumber\": \"PO18009186470\",\"Status\": \"Cancelled\"}")))
{
await client.ReplaceDocumentAsync(readDoc.SelfLink, Resource.LoadFrom<Document>(memoryStream));
}
}

How can I save a json

I do have this code it fund the good value, but it doesn't save the modification. What can I do ?
using (StreamReader r = new StreamReader("C:/Files/generated.json"))
{
string json = r.ReadToEnd();
var result = JsonConvert.DeserializeObject<List<Form>>(json);
foreach (var item in result)
{
if (item.id == FormtoSave.id)
{
item.Title = FormtoSave.Title;
item.body = FormtoSave.body;
}
}
}
After modification in Item title and body you have again serialize object in json and store Json string in file.
TextWriter writer = new StreamWriter("c:\\fileName..json");
writer.WriteLine("Serialized Json string ");
writer.Flush();
writer.Close();
Try this to convert your modified object back to a json:
string jsonOutput= JsonConvert.SerializeObject(result);
Edit:
In order to save the string to a file use this:
string path = #"c:\output.json";
File.WriteAllText(path, jsonOutput);
You need to save the changes back to the file:
string resultJson = String.Empty;
using (StreamReader r = new StreamReader("C:/Files/generated.json"))
{
string json = r.ReadToEnd();
var result = JsonConvert.DeserializeObject<List<Form>>(json);
foreach (var item in result)
{
if (item.id == FormtoSave.id)
{
item.Title = FormtoSave.Title;
item.body = FormtoSave.body;
}
}
resultJson = JsonConvert.SerializeObject(result);
}
File.WriteAllText("C:/Files/generated.json", resultJson);
I did the writing outside the using so the file is not still locked by the StreamReader.
Or not using a StreamReader:
string path = "C:/Files/generated.json";
var result = JsonConvert.DeserializeObject<List<Form>>(File.ReadAllText(path));
foreach (var item in result)
{
if (item.id == FormtoSave.id)
{
item.Title = FormtoSave.Title;
item.body = FormtoSave.body;
}
}
File.WriteAllText(path, JsonConvert.SerializeObject(result));
Below example will help you
List<data> _data = new List<data>();
_data.Add(new data()
{
Id = 1,
SSN = 2,
Message = "A Message"
});
string json = JsonConvert.SerializeObject(_data.ToArray());
//write string to file
System.IO.File.WriteAllText (#"D:\path.txt", json);

Categories