Assign List value to Json list class - c#

I have a List class List<Data> dataValue = new List<Data> where Data contains List of destination's(multiple) and List of source's(multiple) details. I want to loop through and assign each of the destination and source to the List below. I am finally converting all the data to a JSON file.
foreach (var data in dataValue)
{
var value = new RuleJsonclassTemplate
{
type = data.type,
mapping = new List<Mapping>() { new Mapping() { value = data.destination, key = data.source } },
description = data.description,
title = data.title
}
}
string JSONresult = JsonConvert.SerializeObject(value);
string path = outputdir + Outputfilename;
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine(JSONresult.ToString());
writer.Close();
}
class Mapping
{
public string destination { get; set; }
public string source { get; set; }
}
The JSON output should look like below,
{
"type": "Type1",
"mapping": [
{
"value": "destination1",
"key": "source1"
},
{
"value": "destination2",
"key": "source1"
},
{
"value": "destination3",
"key": "source3"
}
],
"description": "Test description",
"title": "Test title"
}
Can you please suggest on how can I achieve this? For reference my sample code at https://dotnetfiddle.net/W49buW

It would be :
public string ConvertToJSON(List<string>SourceStr,List<string>DestinationStr)
{
string json = "{" + Environment.NewLine + "mapping : [" + Environment.NewLine;
for (int i = 0; i < SourceStr.Count; i++)
{
json = json + "{" + Environment.NewLine + "value : " + SourceStr[i].ToString() + ","+ Environment.NewLine
+ "key : " + DestinationStr[i].ToString() + Environment.NewLine + "}," + Environment.NewLine;
}
json = json.Substring(0, json.LastIndexOf(','));
json = json + "]" + Environment.NewLine + "}";
return json;
}

I was able to fix the problem by adding another method which add's the data 1 by 1 to the list. Updated my sample code at https://dotnetfiddle.net/W49buW. Hope this helps for folks looking for the solution.

Related

Checking whether a unique data is present in a json file

I need to check whether a word is present in a JSON file or not. So if I'm searching for "root", then even though the word "byroots" contain root, it should give me false.
Here's my code
using (StreamReader r = new StreamReader("filename.json"))
{
string json1 = r.ReadToEnd();
if (json1.Contains("root"))
{
filename = path + #"" + branch + "-" + testsuite.Title + ".json";
}
}
I've also tried this condition:-
if (json1.IndexOf(testsuite.Title, StringComparison.OrdinalIgnoreCase) >= 0)
But I'm getting the same results.
Here's the json data
{
"LV": {
"build_number": "20180517.1",
"blah_blah": "blah",
"name": "byroots",
}
}
You should use Regex
var pattern = #"*root*";
Regex rgx = new Regex(pattern);
using (StreamReader r = new StreamReader("filename.json"))
{
string json1 = r.ReadToEnd();
if (rgx.IsMatch(json1))
{
filename = path + #"" + branch + "-" + testsuite.Title + ".json";
}
}

Deserialize CSV with CustomHeaders using ServiceStack.Text: not working?

consider following class:
class Foo {
public string bar { get; set; }
public string rab { get; set; }
public override string ToString()
{
return string.Format("[Foo bar={0}, rab={1}]", bar, rab);
}
}
And following code:
var csv1 =
"bar,rab" + Environment.NewLine +
"a,b" + Environment.NewLine +
"c,d" + Environment.NewLine +
"e,f" + Environment.NewLine;
var csv2 =
"xbar,xrab" + Environment.NewLine +
"a,b" + Environment.NewLine +
"c,d" + Environment.NewLine +
"e,f" + Environment.NewLine;
Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv1).First());
CsvConfig<TMDBEntity>.CustomHeadersMap = new Dictionary<string, string> {
{"bar", "xbar"},
{"rab", "xrab"}
};
Console.WriteLine(CsvSerializer.DeserializeFromString<List<Foo>>(csv2).First());
It is printing:
[Foo bar=a, rab=b]
[Foo bar=, rab=]
while I would expect it to print
[Foo bar=a, rab=b]
[Foo bar=a, rab=b]
Why is it not picking up the custom headers using xbar and xrab?
ServiceStack.Text version is 4.5.14.0
This issue should be resolved from this commit which is available from ServiceStack v5.0.0 that's now available on MyGet.
Note you need to configure CsvConfig<Foo> in order to change how Foo is deserialized, e.g:
CsvConfig<Foo>.CustomHeadersMap = new Dictionary<string, string> {
{"bar", "xbar"},
{"rab", "xrab"}
};

C# Saving Permanent Data in ProgramFiles

I am creating a desktop app that needs to save permanent data. The easiest way I could think of doing this is by writing important information about the file to a textfile. Just to make the data contained, professional and easily accessed by the app, I decided to put it in a newly created folder in the "Program Files" directory of the users computer. Unfortunately, this is blocked by the computer. It denies the access to my application. I know my code works because I ran the application as an administrator and encountered no errors. It also created the folder in "Program Files" as I wanted. Is there anyway to allow access. I'd also like to get the users' permission first. The code is posted below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyAppNameSpace
{
static class DataManager
{
/* Create a dictionary that takes type "string" for its
* key (name) and type "object" for its value */
public static Dictionary<string, object> Data = new Dictionary<string, object>();
public static string FileName { get; private set; }
public static string ProgramFilesFolder;
// A method to clear all game data
public static void Clear()
{
}
public static void Save()
{
foreach (KeyValuePair<string, object> DataPair in Data)
{
}
}
public static string GetData()
{
return File.ReadAllText(FileName);
}
public static void Setup()
{
ProgramFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/MyAppName";
FileName = ProgramFilesFolder + "/MyAppData";
if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/MyAppName/README.txt"))
{
try
{
Directory.CreateDirectory(ProgramFilesFolder);
string text = "DO NOT move this folder. If you must, make sure to keep it " +
"in the same location as the SwingState it is. Also, do not edit the " +
"contents of the data file, which exists in this directory. " +
"This saves all of your progress in your game!";
File.WriteAllText(ProgramFilesFolder + "/README.txt", text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ":" + ex.InnerException);
GameInfo.Game.Close();
}
}
if (!File.Exists(FileName))
{
Data = new Dictionary<string, object>()
{
{ "Name:", null + "," },
{ "Age:", null + "," },
{ "Description:", null + "," },
{ "Gender:", null + "," },
{ "Level:", 1 + "," },
{ "Drawing:", false + "," },
{ "Uploaded:", false + "," },
{ "Template:", false + "," },
{ "Left1:", null + "," },
{ "Left2:", null + "," },
{ "Left3:", null + "," },
{ "Right1:", null + "," },
{ "Right2:", null + "," },
{ "Right3:", null + "," },
{ "Idle:", null + "," },
{ "Template Number:", null + "," }
};
}
else if (File.Exists(FileName))
{
string[] DataText = File.ReadAllText(FileName).Split(',');
foreach (string s in DataText)
{
Data.Add(s.Split(':')[0], s.Split(':')[1]);
}
}
}
}
}
I fixed this by changing the special folder to AppData. Here is the code for that:
ProgramFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/MyAppName";
FileName = ProgramFilesFolder + "/MyAppData";
if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/MyAppName/README.txt"))

Correct JSON format for GCM message

heres my JSON
var postData =
"{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ], "+
"\"data\": {\""+ pushNotificationState.NotificationData.NotificationData + "\"}";
registration Id and notification data are variables. I'm getting a 400 response from the GCM sever saying JSON is incorrect format. Can anyone pick where I have gone wrong?
Cheers
You have one open { but have two close }.
var postData = "{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ], " + "\"data\": \""+ pushNotificationState.NotificationData.NotificationData + "\"}";
Use some Json tools, instead of creating your string by hand. Otherwise you'd have problems if some of string variables contain {,}," etc.
var json = JsonConvert.DeserializeObject(
new {
registration_ids = new[] { pushNotificationState.RegistrationId },
data = pushNotificationState.NotificationData.NotificationData
});
var postData = "{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ]}, "+
"\"data\": {\""+ pushNotificationState.NotificationData.NotificationData + "\"}";
Try replacing it with that.
You can use the below code to create the request object, then convert to json.
public class GCMRequest
{
public GCMRequest()
{
data = new PayLoad();
}
public List<string> registration_ids;
public PayLoad data;
}
public class PayLoad
{
public string key;
}
you can create the request as below
GCMRequest req = new GCMRequest();
List<string> tokens = new List<string>();
// .. fill the tokens to the 'tokens' list
req.registration_ids = tokens;
req.data.key = "Hi, how are you"; // message you want to send
string json = new JavaScriptSerializer().Serialize(req);
Hope this will help.

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

I am new to JSON.In my asp.net application i want to parse the json string.So, i have used Newtonsoft.Json package for reading and writing json data.Now, i can able to parse the simple json data.But now i have received some complex json data for parsing.So, i little bit struck on it.
This is JSON Data:
{
quizlist: [
{
QUIZ: {
'QPROP': [
{
'name': 'FB',
'intro': '',
'timeopen': '1347871440',
'timeclose': '1355733840',
'timelimit': '0',
'noofques': '5',
'QUESTION': {
'QUEPROP': [
{
'questiontext': 'Scienceisbasedont',
'penalty': '0.3333333',
'qtype': 'shortanswer',
'answer': 'cause-and-effect',
'mark' : '5',
'hint': ''
},
{
'questiontext': 'otherscientistsevaluateit',
'penalty': '0.3333333',
'qtype': 'shortanswer',
'answer': 'Peerreview',
'mark' : '5',
'hint': ''
},
{
'questiontext': 'Watchingavariety',
'penalty': '0.3333333',
'qtype': 'shortanswer',
'answer': 'inductive',
'mark' : '5',
'hint': ''
},
{
'questiontext': 'coveriesorideas',
'penalty': '0.3333333',
'qtype': 'shortanswer',
'answer': 'paradigmshift',
'mark' : '5',
'hint': ''
},
{
'questiontext': 'proportions',
'penalty': '0.3333333',
'qtype': 'shortanswer',
'answer': 'fixed',
'mark' : '5',
'hint': ''
}
]
}
}
]
}
}
]
}
This is my C# Code :
dynamic dynObj = JsonConvert.DeserializeObject(jsonString);
foreach (var data in dynObj.quizlist)
{
foreach (var data1 in data.QUIZ.QPROP)
{
Response.Write("Name" + ":" + data1.name + "<br>");
Response.Write("Intro" + ":" + data1.intro + "<br>");
Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
Response.Write("Noofques" + ":" + data1.noofques + "<br>");
}
}
I can able to parse until noofques object in QPROP array objects.Now have to parse data.QUIZ.QPROP.QUESTION.QUEPROP array objects also...
But i failed to parse fully...
Please guide me to get out of this issue...
foreach (var data in dynObj.quizlist)
{
foreach (var data1 in data.QUIZ.QPROP)
{
Response.Write("Name" + ":" + data1.name + "<br>");
Response.Write("Intro" + ":" + data1.intro + "<br>");
Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
Response.Write("Noofques" + ":" + data1.noofques + "<br>");
foreach (var queprop in data1.QUESTION.QUEPROP)
{
Response.Write("Questiontext" + ":" + queprop.questiontext + "<br>");
Response.Write("Mark" + ":" + queprop.mark + "<br>");
}
}
}
You can use this tool to create appropriate c# classes:
http://jsonclassgenerator.codeplex.com/
and when you will have classes created you can simply convert string to object:
public static T ParseJsonObject<T>(string json) where T : class, new()
{
JObject jobject = JObject.Parse(json);
return JsonConvert.DeserializeObject<T>(jobject.ToString());
}
Here that classes: http://ge.tt/2KGtbPT/v/0?c
Just fix namespaces.
You could create your own class of type Quiz and then deserialize with strong type:
Example:
quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
new JsonSerializerSettings
{
Error = delegate(object sender1, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
}
});
And you could also apply a schema validation.
http://james.newtonking.com/projects/json/help/index.html
This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
WebClient client = new WebClient();
string jsonstring;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
Response.Write(dynObj.results[0].address_components[1].long_name);
}
}
}

Categories

Resources