Lets say I have this json array stored in a dynamic newtonsoft json object:
[
{
"Name":"Amal",
"Country":"India"
},
{
"Name":"Luke",
"Country":"England"
},
{
"Name":"Tom",
"Country":"Australia"
},
{
"Name":"Ram",
"Country":"India"
},
{
"Name":"Jane",
"Country":"France"
}
]
I need to be able to return the json objects in the array where a name ends with an "e"
Looking for these results:
[{ "Name":"Luke", "Country":"England" }, { "Name":"Jane", "Country":"France" }]
What you need is to use Linq extensions and Value<string>() method of the JToken since JArray is a collection of JTokens. Then build a new JArray with filtered tokens.
var json = "[ { \"Name\":\"Amal\", \"Country\":\"India\" }, { \"Name\":\"Luke\", \"Country\":\"England\" }, { \"Name\":\"Tom\", \"Country\":\"Australia\" }, { \"Name\":\"Ram\", \"Country\":\"India\" }, { \"Name\":\"Jane\", \"Country\":\"France\" }]";
var arr = JArray.Parse(json);
var result = new JArray( arr.Where(r=> r.Value<string>("Name").EndsWith("e")));
Fiddle
Related
In JavaScript I can easily create an object and assign variables with some very basic notation such as:
const Object = JSON.parse('
{
"something": outsideVariable,
"someArray": [
"hey",
"there"
]
}
');
Is there a simple way to do this with C# that is clean and easy to assign variables too? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:
JsonObject jsonPayload = new JsonObject
{
["documentId"] = documentID,
["testMode"] = true,
["signers"] = new JsonArray
{
new JsonObject
{
["label"] = "John Smith",
["contactMethod"] = new JsonArray
{
new JsonObject
{
["type"] = "link"
}
}
}
}
};
I also tried using the literal symbol (#) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.
IMHO , the most close you want is this
var jsonPayload = new
{
documentId = 1,
testMode = true,
signers = new object[]
{
new {
label="John Smith",
contactMethod= new object[]
{
new {
type="link"
}
}
}
}
};
and code
var json= System.Text.Json.JsonSerializer
.Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true });
//or if you need
var jsonParsed= JsonDocument.Parse(json);
result
{
"documentId": 1,
"testMode": true,
"signers": [
{
"label": "John Smith",
"contactMethod": [
{
"type": "link"
}
]
}
]
}
I have a json like below
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1"
}
}
Please suggest how to add
"Address": {
"No": "123",
"Street": "abc"
}
into ContactDetails
This should work (using Newtonsoft.Json)
var json =
#"{
""name"": ""Ram"",
""Age"": ""25"",
""ContactDetails"": {
""MobNo"": ""1""
}
}";
var jObject = JObject.Parse(json);
jObject["ContactDetails"]["Address"] = JObject.Parse(#"{""No"":""123"",""Street"":""abc""}");
var resultAsJsonString = jObject.ToString();
The result is:
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1",
"Address": {
"No": "123",
"Street": "abc"
}
}
}
One of the options would be use Newtonsoft's Json.NET to parse json into JObject, find needed token, and add property to it:
var jObj = JObject.Parse(jsonString);
var jObjToExtend = (JObject)jObj.SelectToken("$.ContactDetails");
jObjToExtend.Add("Address", JObject.FromObject(new { No = "123", Street = "abc" }));
Just Deserialize the JSON into object, then insert the value that you need to insert to it.
Then, Serialize the object into JSON.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
I want to retrieve all the documents of a collection from mongoDB in C# .Net Web API. Below code is working fine but It is returning BsonDocument
var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents);
From above code I am getting data in below format (After JSON.stringify() in angular)
[
[
{
"name":"_id",
"value":"5de9f351baca28556c6a4b71"
},
{
"name":"Name",
"value":"Harsha"
},
{
"name":"Age",
"value":20
},
{
"name":"Gender",
"value":"M"
},
{
"name":"Skills",
"value":[
{
"name":"Java",
"value":""
},
{
"name":"Mule",
"value":true
},
{
"name":"Angular",
"value":""
}
]
}
],
[
{
"name":"_id",
"value":"5de9f358baca28556c6a4b72"
},
{
"name":"Name",
"value":"Anji"
},
{
"name":"Age",
"value":21
},
{
"name":"Gender",
"value":"M"
},
{
"name":"Skills",
"value":[
{
"name":"Java",
"value":""
},
{
"name":"Mule",
"value":true
},
{
"name":"Angular",
"value":true
}
]
}
]
]
How to receive it in proper JSON format OR how to convert this BSON document in JSON as I am unable to process this output.
Try the following, with conversion.
var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents.ToList().ConvertAll(BsonTypeMapper.MapToDotNetValue));
Consider I have a JSON data as:
{
"entities":[
{
"republish": false,
"OrgID": "",
"createdby": "730",
"questions": [
{
"sequence": "5",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 0
},
{
"key": "Part",
"value": "0"
}
]
},
{
"sequence": "4",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 1
},
{
"key": "Part",
"value": "A"
}
]
},
{
"sequence": "3",
"QuestionId": "57BB6DDC-A90A-10EE-E224-EC658A825871",
"metadata": [
{
"key": "Group",
"value": 1
},
{
"key": "Part",
"value": "B"
}
]
}
]
}
]
}
As you can see I have a list of questions available and in each question, I have a metadata which holds Key-Value pair.
Above example demonstrates, I have 3 questions and out of it 2 question, metadata key-value is "Group 1".
Now I want to do is combine the questions with a same key-value pair and treat it as one.
so in my final case, I will have 2 questions instead of 3. And out of that one question will have two separate questions inside.
And I want to achieve this using Linq query. And if possible please use Newtonsoft for parse if needed. I have been stuck for long onto this.
Things I have done:
public virtual HttpResponseMessage AddQuestionsToStandardMaster(TaxonomyMetaData objQuestion)
{
List<ResponseEntity> objResponseList = new List<ResponseEntity>();
try
{
if (ModelState.IsValid)
{
foreach (var objEntity in objQuestion.Entities)
{
EntityResponse objentityresponse = new EntityResponse();
ResponseEntity objResponse = new ResponseEntity();
}
List<Question> objQuestionList = new List<Question>();
if (objEntity.Questions.Length > 0)
{
foreach (var item in objEntity.Questions)
{
int questionTypeid = 0;
dynamic objQuestionJson = JObject.Parse(item.ToString())
}
}
}
Question objCurrentQuestion = new Question();
Question objQuestionforDelete = new Question();
JObject itemToParese = new JObject();
string SingleQuestionJson = objQuestionJson.GetValue("QuestionData").ToString();
string questionstem = "";
Regex rgx = new Regex("/\'");
objCurrentQuestion.Sequence = Convert.ToInt32(objQuestionJson.GetValue("sequence"));
objCurrentQuestion.tag = objQuestionJson.tag.ToObject<JToken[]>(); ;
objCurrentQuestion.metadata = objQuestionJson.metadata.ToObject<JToken[]>();
objCurrentQuestion.SingleQuestionJson = rgx.Replace(SingleQuestionJson, "'");
objCurrentQuestion.QuestionsType = questionTypeid;
objCurrentQuestion.QuestionsId = new Guid(objQuestionJson.GetValue("QuestionId").ToString());
objCurrentQuestion.VersionNo = Convert.ToInt32(objQuestionJson.GetValue("VersionNo"));
objCurrentQuestion.DisplayQuestionId = Convert.ToString(objQuestionJson.GetValue("DisplayQuestionId"));
objCurrentQuestion.OriginalQuestionId = Convert.ToString(objQuestionJson.GetValue("OriginalQuestionId"));
objCurrentQuestion.PassageText = Convert.ToString(objQuestionJson.GetValue("passage_text"));
objCurrentQuestion.PassageCode = Convert.ToString(objQuestionJson.GetValue("passage_id"));
objCurrentQuestion.PassageTitle = Convert.ToString(objQuestionJson.GetValue("passage_title"));
objCurrentQuestion.IsPublished = Convert.ToByte(true);
objCurrentQuestion.ProductId = objEntity.ProductID;
foreach (var metadata in objCurrentQuestion.metadata)
{
switch (metadata["key"].ToString())
{
case "Group":
objCurrentQuestion.Group = Convert.ToInt32(metadata["value"].ToString());
break;
case "Part":
objCurrentQuestion.Part = metadata["value"].ToString();
break;
}
}
objQuestionList.Add(objCurrentQuestion);
int counter = 1;
//Here I get the data in a group which needs to coverted to JSOn and then replace the original JSON data with this. But I know this is irrelevant to what we need to achieve.
var yui = objQuestionList.Where(tma => tma.Group == counter).Select(t => t).GroupBy(s => new { s.Group }).Where(p => p.Count() > 1).ToList();
//After proper conversion I need to enter this data to a database.
I am a bit unclear on what do you mean by make it
combine the questions with a same key-value pair and treat it as one
But here is how you can group by the JSON into groups in metadata you can do a custom select to what ever you want.
var text = #"{
""entities"":[
{
""republish"": false,
""OrgID"": """",
""createdby"": ""730"",
""questions"": [
{
""sequence"": ""5"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 0
},
{
""key"": ""Part"",
""value"": ""0""
}
]
},
{
""sequence"": ""4"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 1
},
{
""key"": ""Part"",
""value"": ""A""
}
]
},
{
""sequence"": ""3"",
""QuestionId"": ""57BB6DDC-A90A-10EE-E224-EC658A825871"",
""metadata"": [
{
""key"": ""Group"",
""value"": 1
},
{
""key"": ""Part"",
""value"": ""B""
}
]
}
]
}
]
}";
var json = JObject.Parse(text);
var groupedData = from entity in json["entities"]
from question in entity["questions"]
group question by question["metadata"][0]["value"] into questionGroup
select questionGroup;
foreach (var data in groupedData)
{
Console.WriteLine("_____________________");
Console.WriteLine("Group");
Console.WriteLine(data.Key);
foreach (var question in data)
{
Console.WriteLine(question["QuestionId"]);
}
Console.WriteLine("_____________________");
}
If "Group" is not always the fist item in the array you can do
question["metadata"].First(md => md.Value<string>("key") == "Group")["value"]
to get it.
i am trying to get a value from a json file using c#. the json file looks more like the below string.
{
"results": [
{
"address_components": [
{
"long_name": "3",
"short_name": "3",
"types": [
"street_number"
]
}
],
"formatted_address": "3, Puppalaguda - Manikonda Main Rd, Sri Laxmi Nagar Colony, Manikonda, Hyderabad, Telangana 500089, India",
"geometry": {
"bounds": {
"northeast": {
"lat": 17.4025788,
"lng": 78.3748307
},
"southwest": {
"lat": 17.4019665,
"lng": 78.3733937
}
},
"location": {
"lat": 17.4023166,
"lng": 78.37417409999999
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 17.4036216302915,
"lng": 78.37546118029151
},
"southwest": {
"lat": 17.4009236697085,
"lng": 78.3727632197085
}
}
},
"place_id": "EmkzLCBQdXBwYWxhZ3VkYSAtIE1hbmlrb25kYSBNYWluIFJkLCBTcmkgTGF4bWkgTmFnYXIgQ29sb255LCBNYW5pa29uZGEsIEh5ZGVyYWJhZCwgVGVsYW5nYW5hIDUwMDA4OSwgSW5kaWE",
"types": [
"street_address"
]
}
]
}
I am looking for the formatted_address element from the json from C#. I am getting lost in JObject, JArray, JToken. I am trying to use NewtonSoft JSON. Thank you.
Using the LINQ-to-JSON API (JObjects) you can get the formatted address easily using the SelectToken method:
JObject obj = JObject.Parse(json);
string address = (string)obj.SelectToken("results[0].formatted_address");
Console.WriteLine(address);
Fiddle: https://dotnetfiddle.net/Fdvqkl
The easiest way would be to have model objects and then call
var rootObject = JsonConvert.DeserializeObject(jsonString);
With jsonString being your input. Then you can retrieve the formatted_address from the first array element like this like this:
var formattedAddress = rootObject.results[0].formatted_address;
Hope it helps.
using Newtonsoft.Json nuget . and do something like that
static void Main(string[] args)
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
change JTokenType.Array to whatever the type u wish , also change the "results" to the property name you wish to extract