Json.net append json file - json

I have the following code which uses Json.net:
class HistorianRecord
{
public string tagname { get; set; }
public string engunits { get; set; }
public string value { get; set; }
public string quality { get; set; }
public DateTime timestamp { get; set; }
}
private static void createJSONFile(DataTable dt)
{
var HistorianData = new List<HistorianRecord>();
foreach(DataRow row in dt.Rows)
{
HistorianData.Add(new HistorianRecord()
{
tagname = row["tagname"].ToString(),
engunits = row["engunits"].ToString(),
value = row["value"].ToString(),
quality = row["quality"].ToString(),
timestamp = DateTime.Parse(row["timestamp"].ToString())
});
}
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(HistorianData);
var deserializedResult = serializer.Deserialize<List<HistorianRecord>>(serializedResult);
File.WriteAllText(folderPath + fileName, JsonConvert.SerializeObject(deserializedResult));
}
Which produces the following JSON file, which I have shortened for this post as the are > 1000 rows in the datatable:
[
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
I would like to amend my code to so I can add some items at the beginning of the JSON file so it looks more like this:
[
{
"name": "ARandomName",
"content": [
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
}
]
This is so I can create some documents for a test MongoDB installation that I am investigating so all help is appreciated.

You simply can wrap your deserialized list of HistorianRecords in an anonymous object and reserialize it:
var anon = new
{
name = "ARandomName",
content = deserializedResult
};
string newJson = JsonConvert.SerializeObject(anon, Formatting.Indented);
Fiddle: https://dotnetfiddle.net/6kSvxS

Related

stream writer is not writing to JSON file in webapi

Im trying to write data in a JSON file using webapi but stream writer is not writing data to the file.
JSON File :
{
"Students": [
{
"id": 1,
"name": "Ravi",
"department": "IT"
},
{
"id": 2,
"name": "Raj",
"department": "hr"
},
{
"id": 3,
"name": "avi",
"department": "it"
},
{
"id": 4,
"name": "rome",
"department": "HR"
},
{
"id":5,
"name": "virat",
"department": "HR"
},
{
"id":6 ,
"name": "Tushar",
"department": "RM"
}
]
}
Class
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
Api controller: [HttpPost] method for writing data to the json file.
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpPost]
public IActionResult Add(Students _Student)
{
using (var fs = new FileStream("C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/people.json", FileMode.Append))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(_Student);
}
}
The data recieved in by _Student is not getting added to the json file.
try this
public IActionResult Add(Students _Student)
{
if(_Student==null || _Student.students==null) return null;
var filePath = #"C:\Users\....\..json";
var json = File.ReadAllText(filePath);
Students students = JsonConvert.DeserializeObject<Students>(json);
students.students.AddRange(_Student.students);
json=JsonConvert.SerializeObject(students);
File.WriteAllText(filePath, json);
}
Try the code like below:
[HttpPost]
public IActionResult Add(Students _Student)
{
string jsonresult = JsonConvert.SerializeObject(_Student);
string path = #"C:\c\people.json";
using(var tw=new StreamWriter(path,true))
{
tw.WriteLine(jsonresult.ToString());
tw.Close();
}
return Ok();
}
result:
Update more picture, add data inside the existing JSON file.

How to extract only part of the JSON and de-serialize it in .netcore

I have .net core application , where an API is called through HTTPClient.
The response for that API in JSON format is as follows:
{
"ID": 25,
"Customer": "CustomerName",
"total": 100,
"details": [
{
"ItemId": "Item1",
"ItemName": "Name1",
"Price": "10"
},
{
"ItemId": "Item2",
"ItemName": "Name2",
"Price": "50"
},
{
"ItemId": "Item3",
"ItemName": "Name3",
"Price": "40"
}
]
}
I get this response from -- > var response = client.GetAsync(ApiPath).Result;
Now from the response variable I need details only for details like :
{
{
"ItemId": "Item1",
"Price": "10"
},
{
"ItemId": "Item2",
"Price": "50"
},
{
"ItemId": "Item3",
"Price": "40"
}
}
I have a DTO class like this :
public class ItemDetails
{
public string ItemId { get; set; }
public string Price { get; set; }
}
Can anyone help in extracting the details according to the DTO class from the main variable "response".
Many thanks!
Try this if you are using newtonsoft
var token = JObject.Parse(response);//load
var detailsToken = token.SelectToken("details");//select
var itemDetails = detailsToken.ToObject<ItemDetails[]>(); //cast to array
Only the properties that exist on ItemDetails will be mapped
You can deserialize the response into an object and take whatever you like from it.
Use the built-in JSON library in .net-core as following
using System.Text.Json;
using System.Text.Json.Serialization;
then make a Response classes to contain the Response values
public class ResponseObject
{
public int ID { get; set; }
public string Customer { get; set; }
[JsonPropertyName("total")]
public int Total { get; set; }
[JsonPropertyName("details")]
public ItemDetails[] Details { get; set; }
}
public class ItemDetails
{
public string ItemId { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
}
finally, deserialize and extract whatever you like as following
var o = JsonSerializer.Deserialize<ResponseObject>(response);
ItemDetails[] itemDetails= o.Details;

HubSpot API POST contacts in batches

I am using the API to communicate batches of contacts using the endpoint /contacts/v1/contact/batch/
I get an error message response which reads#
{"status":"error", "message":"Invalid input JSON on line 1, column 1: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token","correlationId":"3c1488a8-24f5-4e1c-b506-18edcd870065","requestId":"a85c3ea88b60a7d0e3cfe5736c819b11"}
The JSON i am sending is valid. I've checked and double checked.
Please help :(
My output is below
[
{
"email": "twst#email.com",
"properties": [
{
"property": "company",
"value": "Test"
},
{
"property": "website",
"value": "www.test.com"
},
{
"property": "firstname",
"value": "Carl"
},
{
"property": "lastname",
"value": "Swann"
},
{
"property": "jobtitle",
"value": "Dr"
},
{
"property": "phone",
"value": "0789654321"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
},
{
"email": "email#yes .com",
"properties": [
{
"property": "company",
"value": "Another one"
},
{
"property": "website",
"value": "www.a.ither.com"
},
{
"property": "firstname",
"value": "Anither"
},
{
"property": "lastname",
"value": "One"
},
{
"property": "jobtitle",
"value": "Com"
},
{
"property": "phone",
"value": "0789675341"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
},
{
"email": "keeley#sophieallport.com",
"properties": [
{
"property": "company",
"value": "Sophie Allport"
},
{
"property": "website",
"value": "www.sophieallport.com"
},
{
"property": "firstname",
"value": "Keeley"
},
{
"property": "lastname",
"value": "Walters"
},
{
"property": "jobtitle",
"value": "Accounts "
},
{
"property": "phone",
"value": "01778235648"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
}
]
I found the source code I used and will try my best to explain my implementation of it for you.
The application I created was a mobile app that is used by companies to capture information about new prospects and send that information into their HubSpot account.
The main application contains a class of Prospect which defines the information we want to obtain about a prospect
public class Prospect
{
public string CompanyName { get; set; }
public string Website { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string JobTitle { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Products { get; set; }
public string Notes { get; set; }
public string ContactOwner { get; set; }
public string ShowName { get; set; }
}
The component of the application which is relevant to the question you asked contains 2 classes:
public class HubSpotProspect
{
public string email { get; set; }
public List<Property> properties { get; set; }
}
public class Property
{
public string property { get; set; }
public string value { get; set; }
}
The following code gets a list of all the prospects then iterates through them to assign the correct attribute values and translates then into a new list of HubSpotProspect. We then serialise this list into json and pass it to the function that communicates with HubSpot API.
List<Prospect> _pList = _prospectList.GetProspectList(ShowName);
List _hsProspectList = new List();
foreach (Prospect p in _pList)
{
HubSpotProspect _hsp = new HubSpotProspect();
_hsp.email = p.Email;
_hsp.properties = new List<Property>();
_hsp.properties.Add(new Property { property = "company", value = p.CompanyName });
_hsp.properties.Add(new Property { property = "website", value = p.Website });
_hsp.properties.Add(new Property { property = "firstname", value = p.FirstName });
_hsp.properties.Add(new Property { property = "lastname", value = p.LastName });
_hsp.properties.Add(new Property { property = "jobtitle", value = p.JobTitle });
_hsp.properties.Add(new Property { property = "phone", value = p.Phone });
_hsp.properties.Add(new Property { property = "product", value = p.Products });
_hsp.properties.Add(new Property { property = "event_list_2019", value = p.ShowName });
_hsp.properties.Add(new Property { property = "hubspot_owner_id", value = _userProfile.GetContactOwner() });
_hsProspectList.Add(_hsp);
}
string json = JsonConvert.SerializeObject(_hsProspectList);
await SendContact(json);
The function that communicates with the HubSpot API is as follows:
private Task SendContact(string JsonString)
{
return Task.Factory.StartNew(() =>
{
string hapiKey = _userProfile.GetHapiKey();
var client = new RestClient(https://api.hubapi.com/);
var request = new RestRequest("contacts/v1/contact/batch/", Method.POST);
request.AddQueryParameter("hapikey", hapiKey);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(JsonString);
IRestResponse response = client.Execute<HubSpotProspect>(request);
var content = response.Content;
//Console.WriteLine("RESPONSE " + content);
});
}

Creating json object in mvc and returning from controller

I need to create the following in a loop, my has "name" and "id" where name will be used for the value property of the json object and id will be used for the "data" and query will be some string I can set.
I tried using keypair but could not figure out how to do this property. Any help would be appreciated.
{
"query": "Unit",
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
I am trying to return results for this autocomplete widget
https://www.devbridge.com/sourcery/components/jquery-autocomplete/
You can just create an anonymous object. To return the JSON as indicated in your question, it would be
public JsonResult GetCities(string query)
{
var data = new
{
query = "Unit",
suggestions = new[]
{
new { value = "United Arab Emirates", data = "AE" },
new { value = "United Kingdom", data = "UK" },
new { value = "United States", data = "US" }
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
Side note: Unsure of the purpose of the method parameter?
I hate to go full blown on this, but maybe create your own classes?
public class DataValuePair
{
public string Data {get;set;}
public string Value {get;set;}
}
public class SearchResult
{
public string Query {get;set;}
public List<DataValuePair> Suggestions {get;set;}
}
And now you can return a JSON Result
return Json(mySearchResult);
Answer from OP:
Figured it out, below is the code
public ActionResult GetCities(string query)
{
var obj = new CitySuggestion();
obj.suggestions.Add(new Suggestion { value = "test1", data = "test1" });
obj.suggestions.Add(new Suggestion { value = "test2", data = "test2" });
obj.suggestions.Add(new Suggestion { value = "test3", data = "test3" });
return Content(JsonConvert.SerializeObject(obj), "application/json");
}
public class CitySuggestion
{
public CitySuggestion()
{
suggestions = new List<Suggestion>();
}
public List<Suggestion> suggestions
{
get;
set;
}
}
public class Suggestion
{
public string value { get; set; }
public string data { get; set; }
}

How to write a linq query or use a storedprocedure to build a json object in MVC4?

Hi all i have a Database where i have some tables named
[Options],[ProductAttributes],[Products],[ProductSKU],[ProductSKUOptionMappings]
i had added this as entity model to my project,now i want to write a linq query for this where i can get these column from the above specified tables
based on this stored procedure
ALTER procedure [dbo].[GetProductDetail]
(
#ProductID bigint
)
as
begin
Select P.ProductName, P.ProductDescription, PA.SKU, PA.OptionId,O.OptionName, PA.Value, PS.ImageURL from ProductSKU PS
INNER JOIN ProductAttributes PA ON PS.SKU = PA.SKU
INNER JOIN Products P ON P.ProductId = PS.ProductId
INNER JOIN Options O ON O.OptionsId = PA.OptionId
WHERE PS.ProductId = #ProductID
end
i want to convert this query into linq query or use this as Storedprocedure to get my required Json object
the output of my stored procedure looks like this
ProductName ProductDescription SKU OptionId OptionName Value ImageURL
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 1 Color Grey C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 2 Size S C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 3 Fit Regular C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
each product may have different SKUs like the above so can any one help me here how can i build my json object which looks like this
i want my json object to be in this format
var productdetails={
"productId": "1",
"productname": "Casualshirts",
"productSkus": [
{
"Skuimage": "URL",
"SKU": [
{
"ProducSKU": "Shoe1001",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1002",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1003",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
}
]
and here is my model class
public class ProductItems
{
public long ProductID { get; set; }
public string ProductName { get; set; }
public string ImageURL { get; set; }
public List<productSKU> SKUs { get; set; }
}
public class productSKU
{
public string productsku { get; set;}
public string SKUImageURL { get; set;}
public List<options> oPTIONS { get; set; }
}
public class options
{
public long OptionID { get; set; }
public string OptionName { get; set;}
public string OptionValue { get; set;}
}
can any one help me in how to construct my stored procedure or linq query as above json pbjkect thanks in advance...
this is how i am trying to bind my data to my model
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
var data=new List<ProductItems>();
foreach (var prod in productdeatils)
{
ProductItems items = new ProductItems();
items.ProductID = prod.ProductID;
items.ProductName = prod.ProductName;
items.SKUs
}
return data;
}
i am stuck with number of properties in my class and number of Database columns i amn retrieving from my procedure how can i map them to my model
Assuming you have retrieved an instance of your ProductItems model from your data layer you could project it into an anonymous object to be passed to a JsonResult in order to achieve the desired JSON structure:
public ActionResult SomeAction()
{
ProductItems model = ... retrieve the model from your data layer
var result = new
{
productId = model.ProductID,
productname = model.ProductName,
productSkus = model.SKUs.Select(sku => new
{
Skuimage = sku.SKUImageURL,
SKU = new[]
{
new
{
ProducSKU = sku.productsku,
Options = new[]
{
new
{
productOptions = sku.oPTIONS.Select(opt => new
{
OptionID = opt.OptionID,
optionname = opt.OptionName,
value = opt.OptionValue
})
}
}
}
}
})
};
return Json(result, JsonRequestBehavior.AllowGet);
}