How can I save a json - c#

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);

Related

how to insert a data in json text file

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));

Instagram API: How to insert all user media in c# asp.net mvc?

I am trying the get all user media from the instagram api and store into database but how can do that i don't know. i am write the code but using this code just add one media in the database. any one have the idea then please let me know how can do that. here below list the my code.
This is my C# method :
public string makePostFromInstagram()
{
var serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
var nodes1 = serializer1.Deserialize<dynamic>(GetData(strInstagramUserId));
foreach (var date in nodes1)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
int userCount = 0;
foreach (var post in thisNode)
{
if (thisNode[userCount]["username"] == strInstagramUserId)
{
id = thisNode[userCount]["id"].ToString();
}
userCount++;
}
}
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> csObj = serializer.Deserialize<Dictionary<string, object>>(GetRecentPost(id, accessToken));
int length = ((ArrayList)csObj["data"]).Count;
var nodes = serializer.Deserialize<dynamic>(GetRecentPost(id, accessToken));
foreach (var date in nodes)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
foreach (var post in thisNode)
{
UsersOnInstagram objUserInsta = new UsersOnInstagram();
string result = null;
//here i am add just one image so i want to here add multiple image insert
if (post["type"] == "image")
result = UsersOnInstagram.addInstagramPost(strPtId, HttpUtility.UrlEncode(post["caption"]["text"]), post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), null, post["type"]);
else if (post["type"] == "video")
result = objUserInsta.addInstagramPost(HttpUtility.UrlEncode(post["caption"]["text"]), strPtId, post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), post["videos"]["standard_resolution"]["url"], post["type"]);
}
}
}
Response.End();
}
this is my api method :
public static string GetRecentPost(string instagramaccessid, string instagramaccesstoken)
{
Double MAX_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-1));
Double MIN_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-2));
string url = "https://api.instagram.com/v1/users/" + instagramaccessid + "/media/recent?access_token=" + instagramaccesstoken + "&min_timestamp=" + MIN_TIMESTAMP + "&maz_timestamp=" + MAX_TIMESTAMP;
var webClient = new System.Net.WebClient();
string d = webClient.DownloadString(url);
return d;
}
any one know how can do that please let me know.

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"])}");
}

C# Trying to split a string to get json object value

I am trying to split a string to get json object value - I have text values with numerous lines in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
What I would really like is to get them in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },
I know I can use JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. Is there a better way of doing this?
What I have so far:
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(#"c:\Data\temp\output.txt")) // file to write to
{
using (StreamReader reader = new StreamReader(#"c:\Data\temp\test.txt")) //file to read from
{
string line;
while (reader.ReadLine() != null)
{
line = reader.ReadLine();
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
}
}
}
}
static string[] JsonSplitString(string data)
{
return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
}
However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method.
You are calling reader.Readline() twice: once for the comparison and then again inside your loop. You are actually skipping every other line. And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. Try this instead:
line = reader.ReadLine();
while (line != null)
{
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;
namespace JsonExperiments
{
class Program
{
static void Main(string[] args)
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
// mockup JSON that would be returned from API
string sampleJson = "{\"results\":[" +
"{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
"]}";
// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);
// Process each employee
foreach (var result in results["results"])
{
// this can be a string or null
string employeeName = (string)result["employeename"];
// this can be a string or array, how can we tell which it is
JToken supervisor = result["employeesupervisor"];
string supervisorName = "";
if (supervisor is JValue)
{
supervisorName = (string)supervisor;
}
else if (supervisor is JArray)
{
// can pick one, or flatten array to a string
supervisorName = (string)((JArray)supervisor).First;
}
Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
}
}
}
}

How to parse Twitter Search JSON response in C#?

I receive the JSON response from Twitter Search but how can I loop through them?
protected void BtnSearchClick(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://search.twitter.com/search.json?&q=felipe&rpp=40");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);// fill the buffer with data
if (count != 0)// make sure we read some data
{
tempString = Encoding.ASCII.GetString(buf, 0, count);// translate from bytes to ASCII text
sb.Append(tempString);// continue building the string
}
}
while (count > 0); // any more data to read?
//HttpContext.Current.Response.Write(sb.ToString()); //I can see my JSON response here
//object deserializeObject = Newtonsoft.Json.JsonConvert.SerializeObject(sb.ToString());
}
I would make use of dynamic keyword
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://search.twitter.com/search.json?&q=felipe&rpp=40");
dynamic obj = JsonConvert.DeserializeObject(json);
foreach (var result in obj.results)
{
Console.WriteLine("{0} - {1}:\n{2}\n\n", result.from_user_name,
(DateTime)result.created_at,
result.text);
}
}
A strongly typed way..
public class MyTwitterClass
{
public List<CustomObject> data {get; set;}
}
public class CustomObject
{
public string id {get; set;}
public string name {get; set;}
}
Then you should be able to do:
string someJson=
#"{""data"":[{""id"":""1"",""name"":""name1""}, {""id"":""2"",""name"":""name2""}]}";
MyTwitterClass someTwitterData = new JavaScriptSerializer().Deserialize<MyTwitterClass>(someJson);
foreach(var item in someTwitterData.data)
{
Console.Write(item.id + " " + item.name);
}
Having said all that you may want to check this out
http://linqtotwitter.codeplex.com/
Thanks,
The below example should help you, where "result" is the returned JSON
dynamic stuff = JsonConvert.DeserializeObject(result);
foreach (JObject item in stuff)
{
foreach (JProperty trend in item["user"])
{
if (trend.Name == "name")
{
MessageBox.Show(trend.Value.ToString());
}
else if (trend.Name == "followers_count")
{
// GET COUNT
}
else if (trend.Name == "profile_image_url")
{
// GET PROFILE URL
}
}
}

Categories