I am selecting an IEnumerable<dynamic> from the database using Rob Conery's Massive framework. The structure comes back in a flat format Poco C#. I need to transform the data and output it to a Json array (format show at bottom).
I thought I could do the transform using linq (my unsuccessful effort is shown below):
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.ServiceModel.Web;
....
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
JsonArray returnValue = from item in list
select new JsonObject()
{
Name = item.Test,
Data = new dyamic(){...}...
};
Here is the Json I am trying to generate:
[
{
"id": "1",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "",
"column4 name": "the value"
}
]
},
{
"id": "2",
"title": "Data Title",
"data": [
{
"column1 name": "the value",
"column2 name": "the value",
"column3 name": "the value",
"column4 name": "the value"
}
]
}
]
Here is an example using Json.Net
List<int> list = new List<int>() {1 , 2};
string json = JsonConvert.SerializeObject(
list.Select(x => new{
id = x.ToString(),
title = "title " + x.ToString(),
data = Enumerable.Range(3,2).Select(i=> new {column1=i,column2=i*i})
})
, Newtonsoft.Json.Formatting.Indented
);
Output:
[
{
"id": "1",
"title": "title 1",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
},
{
"id": "2",
"title": "title 2",
"data": [
{
"column1": 3,
"column2": 9
},
{
"column1": 4,
"column2": 16
}
]
}
]
OK here is what I ended up with it all looks hunky dory:
[WebGet(UriTemplate = "/tools/data/get?tool={tool}&filters={filters}")]
public JsonArray GetData(string tool, string[,] filters)
{
IEnumerable<dynamic> list = _repository.All("", "", 0).ToList();
IEnumerable<JsonObject> jsonList = from item in list
select new JsonObject()
{
new KeyValuePair<string, JsonValue>("Id", item.Id),
new KeyValuePair<string, JsonValue>("Name", item.Title),
new KeyValuePair<string, JsonValue>("Data", new JsonObject()
{
new KeyValuePair<string, JsonValue>("Product", item.Product),
new KeyValuePair<string, JsonValue>("Suite", item.Suite),
new KeyValuePair<string, JsonValue>("Package", item.Package),
new KeyValuePair<string, JsonValue>("Description", item.Description)
})
};
JsonArray returnValue = new JsonArray(jsonList);
return returnValue;
}
Related
I have such items in Dynamo DB:
[{
"Id": "1",
"Data": {
"Value": "test"
}
},
{
"Id": "2",
"Data": {}
},
{
"Id": "3"
},
{
"Id": "4",
"Data": {
"Wrong": "234"
}
}]
And I'm trying to make it flatten, but for the Data.Value field only:
[{
"Id": "1",
"Value": "test"
},
{
"Id": "2"
},
{
"Id": "3"
},
{
"Id": "4"
}]
My Update request looks like this:
var request = new UpdateItemRequest {
TableName = "<table>",
Key = new Dictionary<string, AttributeValue> {{"Id", new AttributeValue("<item-id>")}},
UpdateExpression = "SET #a = #c.#a REMOVE #c",
ExpressionAttributeNames = new Dictionary<string, string> {
{"#c", "Data"},
{"#a", "Value"}
}
};
This works well for Id = 1 and 3. But does not work for 2 and 4. I assume because it can not do a SET. It does not throw any errors, but simply does not delete the Data attribute.
Is there a way to make it in a single call?
you just need a condition with your expression, to check if the attribute exist or not, thats it.
ConditionExpression ="attribute_exists (#c.#a)"
For more détails in Amazon doncs here.
For example I have a document below for collection = delivery:
{
"doc": [
{
"docid": "15",
"deliverynum": "123",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "16",
"deliverynum": "456",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
is it possible to do a search with "deliverynum" = 999 and the output would be like below?
{
"doc": [
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
or should I make another Collection just for the Doc part?
I am having trouble making a query in C# for this kind of scenario.
In Mongo shell you can use the $(projection) operator:
db.collection.find({ "doc.deliverynum": "999" }, { "doc.$": 1 })
Corresponding C# code can look like below:
var q = Builders<Model>.Filter.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var p = Builders<Model>.Projection.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var data = Col.Find(q).Project(p).ToList();
You can also use q = Builders<Model>.Filter.Empty if you want to get all documents even if the don't contain deliverynum =``999
i am inserting json format but need to know how i can insert in this format as mention below
{
"products": [
{
"product_id": "55",
"name": "testing data",
"price": "77",
"total": "77",
"quantity": "1",
"type": "kg"
}],
],
"totals": [
{
"code": "sub_total",
"title": "Sub-Total",
"text": "Rs277.00",
"value": "277.0000",
"sort_order": "1"
}]
}
here is my code which i am trying
items local = new items();
foreach (var item in _LocalItem){
local = new items
{
name = item.name
};
}
var json = JsonConvert.SerializeObject(local);
var request = new HttpRequestMessage(HttpMethod.Post, "http://orangepotato.rjcpacking.com/index.php?route=api/login/addcustomerOrder");
request.Content = new StringContent(json);
i dont understand where i can add "products" array in json format
Simply: don't serialize an array - serialize something that has an array in a member called products:
var json = JsonConvert.SerializeObject(new { products = local });
I have a Json file as shown below. I want to convert only the option node in the JSON file into a C# ListItemCollection object
ASP.net File:
var path = Server.MapPath(#"~/json.json");
using (StreamReader r = new StreamReader(path,false))
{
string json = r.ReadToEnd();
dynamic arr = JsonConvert.DeserializeObject(json);
ListItemCollection licRB = new ListItemCollection();
licRB = arr.AnswerRadioButton.option;<<-- run time error is produced here
}
JSON File:
{ "FormTitle": "This is Form Title from JSON",
"TitleQuestion1": "This is the Title of Question 1",
"TextQuestion1": "1- This is the text of Quextion Number 1",
"AnswerRadioButton": {
"visible": "true",
"title": "Radio Button Title",
"FieldsetRBStyle": { "border": "1px" },
"option" : [
{
"text": "text1",
"value": "v1",
"checked": "false"
},
{
"text": "text2",
"value": "v2",
"checked": "true"
},
{
"text": "text3",
"value": "v3",
"checked": "false"
},
{
"text": "text4",
"value": "v4",
"checked": "true"
}
] }}
Assuming that you have the required classes (e.g. using this tool) you can access the options like this:
var test = JsonConvert.DeserializeObject<RootObject>(json);
var options = test.AnswerRadioButton.option;
I am trying to create JSON array using Newtonsoft JSON API but its giving me error. I want to achieve structure like
[
{
"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54",
"questions":[
{
"feedback":"6",
"questionid":"1"
},
{
"feedback":"8",
"questionid":"2"
},
{
"feedback":"1",
"questionid":"3"
}
],
"fk_clientid":"24",
"learnerid":"260"
}
]
I want ot add questions array for multiple time but it is giving me error
Can not add property questions to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.
Here is my code:
JArray surveytrackingA = new JArray();
/*code to add
[
{"id":"26",
"appsurvey":"1",
"fk_curriculumid":"70",
"status":"Completed",
"lastaccessedon":"2014-06-20 09:18:54"}]
*/
for (int i = 0; i < surveytrackingA.Count; i++)
{
JObject surveytrackD = (JObject)surveytrackingA[i];
string queryOne = "select * from table101 where fk_curriculumid='"
+ surveytrackD["fk_curriculumid"].ToString()
+ "' and fk_surveyid='"
+ surveytrackD["appsurvey"].ToString() + "'";
JArray questionsA = new JArray();
using (var stmt = await App.localDB.PrepareStatementAsync(queryOne))
{
while (await stmt.StepAsync())
{
JObject questionD = new JObject();
questionD.Add("questionid", stmt.GetTextAt(5));
questionD.Add("feedback", stmt.GetTextAt(6));
questionsA.Add(questionD);
}
}
surveytrackD.Add("questions", questionsA); /*error occurred here when second question array is getting inserted in surveyTrackD*/
surveytrackingA.Add(surveytrackD);
}
Can anyone please correct me. Thanks in advance.
Update:
surveytrackD have the json data,
{
"fk_clientid": "24",
"learnerid": "260",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "completed",
"lastaccessedon": "2014-06-20 09:18:54"
}
You can achieve the same result (JArray in JArray) using regular C# classes and at the end serialize to JSon.
I posted a sample in Github; here a fragment of the code that produces your expected output:
var Surveys = new List<SurveytrackD>();
Surveys.Add( new SurveytrackD { id = "26", appsurvey = "1", fk_curriculumid = "70", status = "Completed", learnerid = "240" } );
Surveys.Add( new SurveytrackD { id = "27", appsurvey = "1", fk_curriculumid = "71", status = "Completed", learnerid = "241" });
foreach (var survey in Surveys)
{
survey.questions = new List<Question>();
survey.questions.Add(new Question { questionid = "1", feedback = "0" });
survey.questions.Add(new Question { questionid = "2", feedback = "1" });
}
var json = JsonConvert.SerializeObject(Surveys, Formatting.Indented);
Console.WriteLine(json);
The output is:
[
{
"fk_clientid": null,
"learnerid": "240",
"appsurvey": "1",
"id": "26",
"fk_curriculumid": "70",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
},
{
"fk_clientid": null,
"learnerid": "241",
"appsurvey": "1",
"id": "27",
"fk_curriculumid": "71",
"status": "Completed",
"lastaccessedon": null,
"questions": [
{
"feedback": "0",
"questionid": "1"
},
{
"feedback": "1",
"questionid": "2"
}
]
}
]