I don't understand how can I output id properly when displaying objects. It's either ObjectId() that I can't parse back to object or some object that has id in it that I can parse but it looks weird.
Note that mapping it to class is not an option, it needs to be fully dynamic because different users have different fields.
Code
public List<object> Get()
{
var client = new MongoClient("mongodb://localhost");
var server = client.GetServer();
var database = server.GetDatabase("api_test");
var collection = database.GetCollection("users");
var json = collection.FindAllAs<BsonDocument>().ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
var obj = JsonConvert.DeserializeObject<List<object>>(json);
return obj;
}
Example
[
{
"_id": {
"$oid": "528e7f9bb1fece903aa9b246"
},
"Name": "Steve",
"Age": 60
},
{
"_id": {
"$oid": "528e7fabb1fece903aa9b247"
},
"Name": "Alice",
"Age": 44
}
]
What I would like
[
{
"_id": "528e7f9bb1fece903aa9b246",
"Name": "Steve",
"Age": 60
},
{
"_id": "528e7fabb1fece903aa9b247",
"Name": "Alice",
"Age": 44
}
]
You can do this by explicitly updating your query result to convert _id to a string before it's serialized to JSON:
var docs = test.FindAll().ToList();
foreach (var doc in docs)
{
doc["_id"] = doc["_id"].ToString();
}
var json = docs.ToJson(
new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
Related
For example we have following document in elastic:
{
"name": "Bob",
"age": "22",
"phrase": "ohohoho",
"date": "2022-10-20T00:00:00Z"
}
string phrase ;
DateTime? date;
Then we want put following:
{
"name": "not Bob",
"age": "22",
"phrase": null,
"date": null
}
in c#:
var updateRequest = new UpdateRequest<T, T>(entity)
{
ScriptedUpsert = true,
Script = new InlineScript(
$"if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}")
{
Lang = "painless",
Params = new Dictionary<string, object>() { { "entity", entity } },
},
Upsert = Activator.CreateInstance<T>()
};
but in the end it will not update phrase and date.
It makes following request:
POST /myIndex/_update/b90278fd-1a66-40bf-b775-d076122c6c02
{
"script": {
"source": ""if (someCondition) {{ctx._source.putAll(params.entity);}} else {{ctx.op = \"noop\";}}"",
"lang": "painless",
"params": {
"entity": {
"name": "",
"age": 22
}
}
},
"upsert": {
"age": 0
}
}
Idk why but it skips all fields with null.
How to update nullable fields to null?
NEST does not support sending null values by default.
You can have a check in script such that if a value is not passed then you can remove it from document.
var updateRequest = new UpdateRequest<T, T(entity)
{
ScriptedUpsert = true,
Script = new InlineScript($"if (params.entity.phrase==null)ctx._source.remove('phrase');")
{
Lang = "painless",
Params = new Dictionary<string, object>() { { "entity", entity } },
},
Upsert = Activator.CreateInstance<T>()
};
You can check for more details here
I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
I would like to convert a csv file into json with nested objects and nested array. The sample csv looks like below. My csv structure can be dynamic, but I am ok to keep it static to get the required format below. I know there are so many answers to similar questions, but none addressing my specific issue of nested objects.
Id,name,nestedobject/id,nestedarray/0/name
1,name,2,namelist
2,name1,3,namelist1
I want the json like below, specifically having trouble with column 3 & 4 (nested objects)
[{"Id": 1,
"name": "name",
"nestedobject": {
"id": 2
},
"nestedarray": [{
"name": "namelist"
}
]
},
{"Id": 2,
"name": "name1",
"nestedobject": {
"id": 3
},
"nestedarray": [
{"name": "namelist1"}]
}
]
Please note to keep the csv file structure dynamic I pass the datatype in the column name - for e.g.. "System.Int32:Id" will be my first column instead of "Id". How can I modify my code to account for the nested objects?
public static DataTable ReadCsvFile(string fileName)
{
DataTable oDataTable = new DataTable();
StreamReader oStreamReader = new StreamReader(fileName);
bool hasColumns = false;
List<string> ColumnNames = new List<string>();
string[] oStreamDataValues = null;
while (!oStreamReader.EndOfStream)
{
String oStreamRowData = oStreamReader.ReadLine();
if(oStreamRowData.Length > 0)
{
oStreamDataValues = oStreamRowData.Split(',');
if(!hasColumns)
{
int i = 0;
foreach(string csvcolumn in oStreamRowData.Split(','))
{
string[] nameWithType = csvcolumn.Split(':');
DataColumn oDataColumn = new DataColumn(nameWithType[1], typeof(string));
ColumnNames.Add(nameWithType[1]);
var type = System.Type.GetType(nameWithType[0]);
oDataColumn.DataType = type;
oDataTable.Columns.Add(oDataColumn);
i = i + 1;
}
hasColumns = true;
}
else
{
DataRow oDataRow = oDataTable.NewRow();
for(int i = 0; i < ColumnNames.Count; i++)
{
oDataRow[ColumnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString();
}
oDataTable.Rows.Add(oDataRow);
}
}
}
oStreamReader.Close();
oStreamReader.Dispose();
return oDataTable;
}
I serialize the DataTable in the end
DataTable dt = ReadCsvFile(filePath);
dt.CaseSensitive = true;
var jsonData = JsonConvert.SerializeObject(dt);
With Cinchoo ETL, an open source library, you can do it as follows
string csv = #"Id,name,nestedobject/id,nestedarray/0/name, nestedarray/0/city, nestedarray/1/name, nestedarray/200/city
1,name,2,namelist10, citylist10,namelist11, citylist11
2,name1,3,namelist20, citylist20,namelist21, citylist21";
StringBuilder json = new StringBuilder();
using (var w = new ChoJSONWriter(json))
{
using (var r = ChoCSVReader.LoadText(csv).WithFirstLineHeader()
.Configure(c => c.NestedColumnSeparator = '/')
)
w.Write(r);
}
Console.WriteLine(json.ToString());
Output:
[
{
"Id": 1,
"name": "name",
"nestedobject": {
"id": 2
},
"nestedarray": [
{
"name": "namelist10",
"city": "citylist10"
},
{
"name": "namelist11"
}
]
},
{
"Id": 2,
"name": "name1",
"nestedobject": {
"id": 3
},
"nestedarray": [
{
"name": "namelist20",
"city": "citylist20"
},
{
"name": "namelist21"
}
]
}
]
Consider I have below values in the drop-down (dropDownList variable) and user selected values are in selectedDropDownValues list.
And DB api returns the list of customers (customerDBList variable).
Now the requirement is to build JSON from selected values as mentioned below -
var dropDownList = new[] { "Customer.Id", "Customer.FirstName", "Customer.LastName", "Customer.Address.AddressLine1", "Customer.Address.AddressLine2" };
var selectedDropDownValues = new[] { "Customer.Id", "Customer.FirstName", "Customer.Address.AddressLine1" };
var customerDBList = new List<Customer>(){
new Customer {
Id=1,
FirstName="John",
LastName="Desouza",
Address=new Address{
AddressLine1="1 Street",
AddressLine2="Linking Road"
}},
new Customer {
Id=2,
FirstName="Sam",
LastName="Lewis",
Address=new Address{
AddressLine1="Fedral Highway",
AddressLine2="Louisville"
}
}};
Expected JSON output as -
[
{
"Customer": {
"Id": 1,
"FirstName": "John",
"Address": {
"AddressLine1": "1 Street"
}
}
},
{
"Customer": {
"Id": 2,
"FirstName": "Sam",
"Address": {
"AddressLine1": "Fedral Highway"
}
}
}
]
As it happens, your selectedDropDownValues strings "Customer.Address.AddressLine1" are in JSONPath syntax, so you could convert your Customer objects to an intermediate JObject then prune unwanted values using JsonExtensions.RemoveAllExcept(this JObject obj, IEnumerable<string> paths) from this answer to How to perform partial object serialization providing "paths" using Newtonsoft JSON.NET.
Note that your desired JSON has an extra level of nesting { "Customer": { ... } } not present in your data model, so it will need to be manually inserted before filtering:
var rootName = "Customer";
var query = customerDBList
// Convert to JObject
.Select(c => JObject.FromObject(c))
// Add additional level of object nesting { "Customer": { ... } }
.Select(o => new JObject( new JProperty(rootName, o)))
// Remove all but selected properties.
.Select(o => o.RemoveAllExcept(selectedDropDownValues));
var json = JsonConvert.SerializeObject(query, Formatting.Indented);
Working sample .Net fiddle here which shows the generated JSON to be, as required,
[
{
"Customer": {
"Id": 1,
"FirstName": "John",
"Address": {
"AddressLine1": "1 Street"
}
}
},
{
"Customer": {
"Id": 2,
"FirstName": "Sam",
"Address": {
"AddressLine1": "Fedral Highway"
}
}
}
]
I am executing a linq query which gets me all the records from a table:
var data = _context.People.ToList(); //_context is my DataContext.
The above returns the the value:
{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}
but according to jsonlint, this is invalid and I need to have it be returned as:
[{
"name": "john",
"age": "30"
},
{
"name": "jane",
"age": "31"
}]
How can I do this?
viewData.xldata = [];
$.each(data, function(i, row) {
var strRow = JSON.stringify(row);
viewData.xldata.push(strRow);});
Deserialize using `JavaScriptSerializer:
var people = jss.Deserialize<List<People>>(args["xldata"]);
Try this:
List<People> data= _context.People.ToList();
System.Web.Script.Serialization.JavaScriptSerializer objSerializer = default(System.Web.Script.Serialization.JavaScriptSerializer);
objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return objSerializer.Serialize(data);