My first JSON is as follows
[{
"UserId": 4,
"FirstName": "rupesh",
"LastName": "Abc",
"Email": "abc#gmail.com",
"Gender": "Male"
}]
My Second JSON is as follows
[{
"AccountId": 2,
"AccountName": "rupeshinfo",
"AccountDomain": null,
"RoleId": 1,
"UserId": 4
}, {
"AccountId": 3,
"AccountName": "Rameshinfo",
"AccountDomain": null,
"RoleId": 2,
"UserId": 4
}]
the result must be
{
"UserDetails": [{
"UserId": 4,
"FirstName": "rupesh",
"LastName": "Abc",
"Email": "abc#gmail.com",
"Gender": "Male"
}],
"AccountDetails": [{
"AccountId": 2,
"AccountName": "rupeshinfo",
"AccountDomain": null,
"RoleId": 1,
"UserId": 4
}, {
"AccountId": 3,
"AccountName": "Rameshinfo",
"AccountDomain": null,
"RoleId": 2,
"UserId": 4
}]
}
If you don't want to mess with string inserts you can go with (and I recommend so) using dynamic objects:
var javaScriptSerializer = new JavaScriptSerializer();
var userDetails = javaScriptSerializer.DeserializeObject(json1);
var accountDetails = javaScriptSerializer.DeserializeObject(json2);
var resultJson = javaScriptSerializer.Serialize(new {UserDetails = userDetails, AccountDetails = accountDetails});
You can deserialize them into two objects, create new anonimous type of these objects, and serialize them into the end one json:
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
var result = jsonSerializer.Serialize(new
{
UserDetails = jsonSerializer.DeserializeObject(#"[{
'UserId': 4,
'FirstName': 'rupesh',
'LastName': 'Abc',
'Email': 'abc#gmail.com',
'Gender': 'Male'
}]"),
AccountDetails = jsonSerializer.DeserializeObject(#"[{
'AccountId': 2,
'AccountName': 'rupeshinfo',
'AccountDomain': null,
'RoleId': 1,
'UserId': 4
}, {
'AccountId': 3,
'AccountName': 'Rameshinfo',
'AccountDomain': null,
'RoleId': 2,
'UserId': 4
}]")
});
Try this
var jsonStr ='{"UserDetails":[{"UserId": 4,"FirstName": "rupesh","LastName": "Abc","Email": "abc#gmail.com","Gender": "Male"}]}'
var obj = JSON.parse(jsonStr);
obj['AccountDetails'].push({"AccountId": 2,"AccountName": "rupeshinfo","AccountDomain": null,"RoleId": 1,"UserId": 4}, {"AccountId": 3,"AccountName": "Rameshinfo","AccountDomain": null,"RoleId": 2,"UserId": 4});
jsonStr = JSON.stringify(obj);
Related
I have the following JSON string:
[
{
"Id": 1,
"UserName": "Test1",
"UserPassword": "Test1",
"FirstName": "TF1",
"LastName": "TL1",
"Mobile": "Test1",
"Email": "TE1",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 4,
"UserName": "Test4",
"UserPassword": "Test4",
"FirstName": "T4F",
"LastName": "TL4",
"Mobile": "Test4",
"Email": "TE4",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 3,
"UserName": "Test3",
"UserPassword": "Test3",
"FirstName": "TF3",
"LastName": "TL3",
"Mobile": "Test3",
"Email": "TE3",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 7,
"UserName": "Test7",
"UserPassword": "Test7",
"FirstName": "T7F",
"LastName": "TL7",
"Mobile": "Test7",
"Email": "TE7",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": 7,
"UserName": "Test7",
"UserPassword": "Test7",
"FirstName": "T7F",
"LastName": "TL7",
"Mobile": "Test7",
"Email": "TE7",
"CreatedDate": "2022-05-29T00:00:00.000Z"
},
{
"Id": null,
"UserName": "PT",
"UserPassword": "PT",
"FirstName": null,
"LastName": null,
"Mobile": null,
"Email": null,
"CreatedDate": null
},
{
"Id": null,
"UserName": "CTest",
"UserPassword": "CTest",
"FirstName": null,
"LastName": null,
"Mobile": null,
"Email": null,
"CreatedDate": null
},
{
"Id": 5,
"UserName": "Test5",
"UserPassword": "Test5",
"FirstName": "TF5",
"LastName": "TL5",
"Mobile": "Test5",
"Email": "TE5",
"CreatedDate": "2022-05-29T00:00:00.000Z"
}
]
And would like to read the all the values of the UserName & UserPassword fields of the string into the following lists:
var UserName = new List<string>();
var UserPassword = new List<string>();
Create a class containing at least those two properties (it could have the others also):
class User
{
public string UserName;
public string UserPassword;
}
Parse the JSON using a suitable parser, such as Json.NET
var list = JsonConvert.DeserializeObject<List<User>>(yourJson);
Use Linq to pull out the data you want
var UserName = list.Select(u => u.UserName).ToList();
var UserPassword = list.Select(u => u.UserPassword ).ToList();
dotnetfiddle
From your JSON string
string JSON_String = ...;
You can also extract the data you want with the help of Regex and LINQ. Here is an example
var UserName = Regex
.Matches(JSON_String, "\"UserName\":\\s*\"\\w+\"")
.Cast<Match>()
.Select(m => m.Value)
.Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
.Select(s => s.Substring(1, s.Length - 2))
.ToList();
var UserPassword = Regex
.Matches(JSON_String, "\"UserPassword\":\\s*\"\\w+\"")
.Cast<Match>()
.Select(m => m.Value)
.Select(s => Regex.Match(s, "\"\\w+\"", RegexOptions.RightToLeft).Value)
.Select(s => s.Substring(1, s.Length - 2))
.ToList();
I need to get values from the JSON below, for example how to index Id in Info?
The whole JSON consists of many matches, this just one with Id 5aa891cd1e1422452e8b4567, and this is a structure of one match.
I try with:
var jsonDATA = JObject.Parse(data);
foreach (var e in jsonDATA["events"]) {
//in this step, the result is JSON below
var id = e["info"]["id"];` // error: cannot access child value on newtonsoft json linq jproperty
}
Any ideas?
{"5aa891cd1e1422452e8b4567": {
"info": {
"id": "5aa891cd1e1422452e8b4567",
"event_id": "58911142245284567",
"name": "Santos Laguna vs Queretaro",
"sport": "Soccer",
"league": "Mexico Cup",
"period": "Finished",
"score": "1:0",
"status": "Live",
"start_time": "2018.03.14 03:06:53",
"state": 1017,
"state_name": "Fulltime",
"minute": 90,
"safe": false,
"safe2": false,
"blocked": false,
"stop": false
},
"stats": {
"home": {
"name": "Santos Laguna",
"color": "",
"position": "",
"on_target": "",
"off_target": "",
"attacks": "",
"dangerous_attacks": "",
"possession": "",
"goals": 1,
"corners": 5,
"yellowcards": 1,
"redcards": 0,
"throwins": 0,
"freekicks": 0,
"goalkicks": 0,
"penalties": 0,
"substitutions": 3,
"ht_result": 1
},
"away": {
"name": "Queretaro",
"color": "",
"position": "",
"on_target": "",
"off_target": "",
"attacks": "",
"dangerous_attacks": "",
"possession": "",
"goals": 0,
"corners": 8,
"yellowcards": 3,
"redcards": 1,
"throwins": 0,
"freekicks": 0,
"goalkicks": 0,
"penalties": 0,
"substitutions": 3,
"ht_result": 0
}
},
"odds": []
}}
You can use anonymous type deserialization for your data like this. Hope it works.
//using Newtonsoft.Json;
var jsonData = JsonConvert.DeserializeAnonymousType(
data,
new
{
events = new[]
{
new
{
Id = new { info = "", stats = "", away = "", odds = "" }
}
}
);
foreach(var item in jsonData.events)
{
var id=item.info.id; // getting id present in info
}
I am trying to Parse a schema and read an element from it however I am getting an error.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Newtonsoft.Json.Schema;
namespace ConsoleApplication1
{
class Test
{
static void Main(string[] args)
{
string ingameschemaFilePath = #"C:\Users\Andrew\Documents\GitHub\SteamBot\Bin\Debug\ingameschema.txt";
string dota2schemaFilePath = #"C:\Users\Andrew\Documents\GitHub\SteamBot\Bin\Debug\dota2schema.txt";
string schemaFilePath = #"C:\Users\Andrew\Documents\GitHub\SteamBot\Bin\Debug\schema.txt";
JsonSchema dota2schema = JsonSchema.Parse(File.ReadAllText(dota2schemaFilePath));
Console.WriteLine(dota2schema.result.items.name);
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
And this is the error I am getting:
Error 2 'Newtonsoft.Json.Schema.JsonSchema' does not contain a definition for 'result' and no extension method 'result' accepting a first argument of type 'Newtonsoft.Json.Schema.JsonSchema' could be found (are you missing a using directive or an assembly reference?)
I am trying to follow the sample here:
http://james.newtonking.com/projects/json/help/#
Samples -> JsonSchema -> Parse Json schema
And here is the start of the schema I am trying to read from:
{
"result": {
"status": 1,
"items_game_url": "http:\/\/media.steampowered.com\/apps\/570\/scripts\/items\/items_game.d8ab2f9911cea9d7f4bce1add62c7bb83a902322.txt",
"qualities": {
"normal": 0,
"genuine": 1,
"vintage": 2,
"unusual": 3,
"unique": 4,
"community": 5,
"developer": 6,
"selfmade": 7,
"customized": 8,
"strange": 9,
"completed": 10,
"haunted": 11,
"tournament": 12,
"favored": 13
},
"originNames": [
{
"origin": 0,
"name": "Timed Drop"
},
{
"origin": 1,
"name": "Achievement"
},
{
"origin": 2,
"name": "Purchased"
},
{
"origin": 3,
"name": "Traded"
},
{
"origin": 4,
"name": "Crafted"
},
{
"origin": 5,
"name": "Store Promotion"
},
{
"origin": 6,
"name": "Gifted"
},
{
"origin": 7,
"name": "Support Granted"
},
{
"origin": 8,
"name": "Found in Crate"
},
{
"origin": 9,
"name": "Earned"
},
{
"origin": 10,
"name": "Third-Party Promotion"
},
{
"origin": 11,
"name": "Wrapped Gift"
},
{
"origin": 12,
"name": "Halloween Drop"
},
{
"origin": 13,
"name": "Steam Purchase"
},
{
"origin": 14,
"name": "Foreign Item"
},
{
"origin": 15,
"name": "CD Key"
},
{
"origin": 16,
"name": "Collection Reward"
},
{
"origin": 17,
"name": "Preview Item"
},
{
"origin": 18,
"name": "Steam Workshop Contribution"
},
{
"origin": 19,
"name": "Periodic Score Reward"
},
{
"origin": 20,
"name": "Recycling"
},
{
"origin": 21,
"name": "Tournament Drop"
},
{
"origin": 22,
"name": "Passport Reward"
},
{
"origin": 23,
"name": "Tutorial Drop"
}
]
,
"items": [
{
"name": "Riki's Dagger",
"defindex": 0,
"item_class": "dota_item_wearable",
"item_type_name": "#DOTA_WearableType_Daggers",
"item_name": "#DOTA_Item_Rikis_Dagger",
"proper_name": false,
"item_quality": 0,
"image_inventory": null,
"min_ilevel": 1,
"max_ilevel": 1,
"image_url": "",
"image_url_large": "",
"capabilities": {
"can_craft_mark": true,
"can_be_restored": true,
"strange_parts": true,
"paintable_unusual": true,
"autograph": true
I thought I did pretty much exactly what the sample did. What have I done wrong? I have searched for similar problems but have not found the answer. Also, if you could let me know the correct way of getting the Def index of "Riki's Dagger" from the json schema that would be great.
If you want to read an element from JSON.
Generate classes from your JSON using http://json2csharp.com/ or http://jsonclassgenerator.codeplex.com/ (I feel this is better).
Use JSON.net to deserialize your JSON into root class.
var ouput -JsonConvert.Deserialize<your_root_class>(JSONString);
Just read the value you want to.
I have some problems with jobject and jarray linq query. I get this error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
My code:
string fetchResult = JsonConvert.SerializeObject(sidebar, Formatting.Indented);
JObject rss = JObject.Parse(fetchResult);
var jsonModel = from item in (JArray)rss["RegistrationCase"]
select new DataList
{
RegistrationTypeName = item["RegistrationTypeName"].Value<string>(), };
If i remove (Jarray) i get: Cannot access child value on Newtonsoft.Json.Linq.JProperty.
Json, jobject: e.g: i want RegistrationTypeName, FirstName and the value of JournalNumber.
{
"Status": null,
"RegistrationCase": {
"RegistrationTypeName": " ",
"ExpireDate": null,
"PersonId": 7,
"Person": {
"FirstName": " ",
"GenderValue": 2,
"Gender": 2,
},
"UserId": 7,
"User": {
"UserName": "NO-DOM\\wme",
"LastName": null,
"Id": 7,
},
"Transactions": [],
"Comments": [],
"CustomData": [
{
"Key": "JournalNumber",
"Value": "0654-84148-00000-25",
"Id": 3,
},
{
"Key": "IsConsentGiven",
"Value": "False",
"Id": 4,
},
{
],
"FileId": null,
"File": null,
"Id": 7,
}
}
u can get these values directly like :
var RegistrationTypeName = rss["RegistrationCase"]["RegistrationTypeName"];
var FirstName = rss["RegistrationCase"]["Person"]["FirstName"];
var JournalNumber = rss["RegistrationCase"]["CustomData"][0]["Value"];
The following code:
var data = _context.People.ToList(); //_context is my DataContext.
produces the result:
[{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }]
but, I want it to be a dictionary, so something like:
{ "xldata" : [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }] }
I got it to work by doing:
Dictionary<string,List<People>> vals = new Dictionary<string, List<People>>();
vals.Add("xldata", people);
but, my dictionary's value is System.Object[] instead of the people
The purpose of this is to export data, so when I get to this line:
var people = jss.Deserialize<List<People>>(args["xldata"]);
args["xldata"] is `System.Object[]` and it says `Invalid JSON primitive`.
Here is the script is supposed to export the data to excel:
$.post(urlContent + exportHandlerPath, Json, function(data) {
var viewData = {};
viewData.xldata = JSON.stringify(data);
html = ich.excelExportTemplate(viewData);
$excelExportContainer.html(html);
var input = $excelExportContainer.find('input#excelExportHiddenField');
input.val(viewData.xldata);
var $excelForm = $('#excelExportForm');
$excelForm.attr('action', '/People/ExportToExcel/');
$excelForm.submit();
}
Apparently your args["xldata"] does not contain a json string like [{ "name": "john", "age": "30" }, { "name": "jane", "age": "31" }], but something returned by a .net object .ToString().
With JavaScriptSerializer.Deserialize you can only deserialize json represenations.