1

I have a script for saving to file sorted, however I cant code it to save to entry: as below

{
    "entry": [
        { "Name": "John" },
        { "Name": "Anna" },
        { "Name": "Peter" }
    ]
}

Im using json.Net, code below needs to add to entry: name

 string json = JsonConvert.SerializeObject(results, Formatting.Indented);
 string path = @"C:\inetpub\wwwroot\JSON\json.Net\results.json";

 if (!File.Exists(path))
 {
     File.WriteAllText(path, json);
 }
 else
 {
     File.AppendAllText(path, json);
 }

I haven't been able to find any good json code samples, cheers Paul

2
  • 2
    Please provide problem details - do you have some error, or not expected results? What results do you expect? Commented Jun 1, 2015 at 7:30
  • You can use FileStream, write an extension method, create a wrapper class. Commented Jun 1, 2015 at 7:30

1 Answer 1

1

I managed it like so!

  UserInfo results = new UserInfo
    {
        Name = Request["name"],

    };

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    JsonWriter jsonWriter = new JsonTextWriter(sw);
    jsonWriter.Formatting = Formatting.Indented;
    jsonWriter.WriteStartObject();
    jsonWriter.WritePropertyName("Name");
    jsonWriter.WriteValue(results.Name);
    jsonWriter.WriteEndObject();

    string json = sw.ToString();
    jsonWriter.Close();
    sw.Close();

    string path = @"C:\inetpub\wwwroot\JSON\json.Net\results.json";

    if (!File.Exists(path))
    {
        File.WriteAllText(path, json);
    }
    else
    {
        File.AppendAllText(path, json);
    }

}

// create a class object to hold the JSON value
public class UserInfo
{
    public string Name { get; set; }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.