While Deserialize the json string from the api "https://jsonplaceholder.typicode.com/posts" - json-deserialization

I'm experiencing An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsoleApplication3.Program+UserData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly..
{
class Program
{
public class UserData
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
static void Main(string[] args)
{
string url = #"https://jsonplaceholder.typicode.com/posts";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
// json-formatted string from api
var responseFromServer = reader.ReadToEnd();
UserData udata = JsonConvert.DeserializeObject<UserData>(responseFromServer);//getting error connot deserialize
}
}
}

I guess what you need is ...
change
UserData udata = JsonConvert.DeserializeObject<UserData>(responseFromServer);
to UserData udata = JsonConvert.DeserializeObject<List<UserData>>(responseFromServer);
Notice <UserData> vs List<UserData>, that is the only variation.
Could you please try this?
EDIT :
Adding code and rextester - http://rextester.com/IRUB82213
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
string responseFromServer = #"
[{
'userId': 1,
'id': 1,
'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'
},
{
'userId': 1,
'id': 2,
'title': 'qui est esse',
'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla'
}]";
var usersData = JsonConvert.DeserializeObject<List<UserData>>(responseFromServer);
foreach(var userData in usersData){
Console.WriteLine(userData.id);
}
}
public class UserData
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
}
}

Related

Deserialize Cosmos SQL API query results List for index view in ASP. NET

I'm working on the ASP.NET Cosmos template.
I change the Model in:
{
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
public class Richieste
{
[JsonProperty(PropertyName="id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string? Name { get; set; }
[JsonProperty(PropertyName = "contact")]
public IList<Contact>? Contacts { get; set; }
[JsonProperty(PropertyName ="regdate")]
[DataType(DataType.Date)]
public DateTime? RegDate { get; set; }
[JsonProperty(PropertyName = "description")]
public string? Description { get; set; }
[JsonProperty(PropertyName ="note")]
[DataType(DataType.MultilineText)]
public string? Note { get; set; }
}
public class Contact
{
[JsonProperty(PropertyName = "contacttype")]
public string? ContactType { get; set; }
[JsonProperty(PropertyName = "contactvalue")]
public string? ContactValue { get; set; }
}
}
My data Model in JSON is:
{
"id": "a8e33584-3d67-4b11-a4a0-a7c463cbe0c9",
"name": "TestName",
"contact": [
{
"contacttype": "11",
"contactvalue": "111"
},
{
"contacttype": "22",
"contactvalue": "222"
},
{
"contacttype": "33",
"contactvalue": "333"
}
],
"regdate": "2022-10-01T08:30:18.8071788+02:00",
"description": "testDescription",
"note": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}
My services for index view are:
public async Task<IEnumerable<Richieste>> GetItemsAsync(string queryString)
{
var query = this._container.GetItemQueryIterator<Richieste>(new QueryDefinition(queryString));
List<Richieste> results = new List<Richieste>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
and my controller is:
// GET: RichiesteController
[ActionName("Index")]
public async Task<ActionResult> Index()
{
return View(await _context.GetItemsAsync("SELECT * FROM c"));
}
When I call the Index method in Controller I receive a json deserialization error.
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[CIS5.Models.Contact]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path '[44].contact.contacttype', line 1, position 15982.
How should I deserialize my model?
I try to modify the GetItemsAsync service:
public async Task<IEnumerable<Richieste>> GetItemsAsync(string queryString)
{
var query = this._container.GetItemQueryIterator<Richieste>(new QueryDefinition(queryString));
List<Richieste> results = new List<Richieste>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
var obj = JsonSerializer.Deserialize<List<Richieste>>(results);
return obj;
}
But it doesn't run, the error is:
I think I found the solution to my question.
After reading more then a lot about Cosmos DB and No-SQL DB, I finally understand that the Model is the key to almost everything happens with Cosmos DB working App.
I put a IList as subdocument in my model but it was just a sub-document so I modified my model in the row where:
public IList<Contact> Contacts { get; Set; }
with the correct notation for my issue
public Contact[] Contacts { get; Set; }
I remove the unuseful line code from services:
var obj = JsonSerializer.Deserialize<List<Richieste>>(results);
and everything runs.
Thank you everyone whos read my post and I'm sorry if my question was so simple.

MS Graph Create open extension call with Json object

I am trying to create events using MS Graph. We are using json objects with the call as in this example
using (HttpClient httpClient = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msBearerToken);
var callJson = new
{
Subject = EventSummery.Title,
Body = new
{
ContentType = BodyType.Html.ToString(),
Content = EventSummery.Description
},
Start = new
{
DateTime = EventSummery.StartDateUTC.ToString("yyyy-MM-ddTHH:mm:ss"),
TimeZone = "GMT Standard Time"
},
End = new
{
DateTime = EventSummery.EndDateUTC.ToString("yyyy-MM-ddTHH:mm:ss"),
TimeZone = "GMT Standard Time"
}
};
I need to add an open extension however the documentation I need to add this attribute
"extensions": [
{
"#odata.type": "microsoft.graph.openTypeExtension",
"extensionName": "Com.Contoso.Referral",
"companyName": "Wingtip Toys",
"expirationDate": "2015-12-30T11:00:00.000Z",
"dealValue": 10000
}]
however #odata.type throws an error if I put it in this form:
Extensions = new
{
"#odata.type": "microsoft.graph.openTypeExtension",
"extensionName": "Com.Contoso.Referral",
"companyName": "Wingtip Toys",
"expirationDate": "2015-12-30T11:00:00.000Z",
"dealValue": 10000
}
What am I missing how can I make this call successfully?
I'm afraid that you cannot create anonymous object with property that has a special character at the beginning.
Only way is to create a class with properties that have JsonPropertyName attribute and then use json serializer.
public class OpenTypeExtension
{
[JsonPropertyName("#odata.type")]
public string ODataType { get; set; }
[JsonPropertyName("extensionName")]
public string ExtensionName { get; set; }
[JsonPropertyName("companyName")]
public string CompanyName { get; set; }
[JsonPropertyName("expirationDate")]
public string ExpirationDate{ get; set; }
[JsonPropertyName("dealValue")]
public string DealValue{ get; set; }
public OpenTypeExtension()
{
ODataType = "microsoft.graph.openTypeExtension";
}
}

Neo4j RelationshipEntity and Spring JPA

I have the following nodes and relationships defined:
CarMaker and Models
A CarModel is made CarMaker in multiple years, and that is represented as a property of the MADE_IN relationship.
A CarModel is made by one CarMaker only.
A CarMaker can make multiple CarModels in multiple years.
I have defined the following Classes to represent the nodes: CarModel, CarMaker and the relationship MADE_IN
CarModel
#NodeEntity
public class CarModel {
private Long id;
private String name;
#Relationship (type="MADE_IN", direction = Relationship.UNDIRECTED)
private Set<MadeIn> madeIns = new HashSet<MadeIn>();
private Set<String> years = new HashSet<String>();
public CarModel() {
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addMadeIn(MadeIn madeIn) {
System.out.println ("Found CarMaker: " + madeIn.getCarMaker());
this.madeIns.add(madeIn);
}
private Set<MadeIn> getMadeIn() {
return madeIns;
}
public Set<String> getYears() {
Iterator<MadeIn> itr = madeIns.iterator();
while (itr.hasNext()) {
years.add(((MadeIn) itr.next()).getYear());
}
Set<String> sortedYears = years.stream().collect(Collectors.toCollection(TreeSet::new));
return sortedYears;
}
}
CarMaker
public class CarMaker {
#GraphId private Long id;
private String name;
#Relationship (type="MADE_IN", direction = Relationship.UNDIRECTED)
private Set<CarModel> carModels = new HashSet<>();
public CarMaker() {
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<CarModel> getCarModels() {
return carModels;
}
public void setCarModels(CarModel carModel) {
carModels.add(carModel);
}
}
MADE_IN
#RelationshipEntity(type="MADE_IN")
public class MadeIn {
#GraphId private Long relationshipId;
#Property private String year;
#StartNode private CarMaker carMaker;
#EndNode private CarModel carModel;
public MadeIn() {
}
public MadeIn(CarMaker carMaker, CarModel carModel, String year) {
this.carMaker = carMaker;
this.carModel = carModel;
this.year = year;
}
public Long getRelationshipId() {
return relationshipId;
}
public void setCarMaker(CarMaker carMaker) {
this.carMaker = carMaker;
}
public CarMaker getCarMaker() {
return this.getCarMaker();
}
public void setCarModel(CarModel carModel) {
this.carModel = carModel;
}
public CarModel getCarModel() {
return this.getCarModel();
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
When I make a request to retrieve a CarModel, I receive a response with the details of that model and all years when it was manufactured:
{
"id": 260248,
"name": "Ulysse",
"years": [
"1994",
"1995",
"1996",
"1997",
"1998",
"1999",
"2000",
"2001",
"2004",
"2005",
"2006",
"2007",
"2008",
"2009",
"2010",
"2011",
"2012"
]
}
The problem is when I try to request the CarModels made by a CarMaker:
{
"id": 4152072,
"name": "BMW",
"carModels": []
}
I noticed that if I reverse the annotations #StartNode and #EndNode on the MadeIn class I get the information about the CarModels made by a CarMaker, however I will not longer get the information about the years when those models were made.
{
"id": 4152072,
"name": "BMW",
"carModels": [
{
"id": 260852,
"name": "120",
"years": []
},
{
"id": 261430,
"name": "Z18",
"years": []
},
{
"id": 262044,
"name": "L7",
"years": []
},
Any idea on what am I missing, or what I am doing wrong ?
Thanks in advance for any help.
--MD

Spring Data Neo4j 4.2.0.BUILD-SNAPSHOT OGM 2.1.0-SNAPSHOT NullPointerException

On the latest Spring Data Neo4j 4.2.0.BUILD-SNAPSHOT and OGM 2.1.0-SNAPSHOT my tests failed with a following NPE(a few days ago everything worked fine and no single line of my code has not been changed):
java.lang.NullPointerException
at org.neo4j.ogm.entity.io.EntityAccessManager.getRelationalReaders(EntityAccessManager.java:355)
at org.neo4j.ogm.context.EntityGraphMapper.bothWayMappingRequired(EntityGraphMapper.java:893)
at org.neo4j.ogm.context.EntityGraphMapper.mapEntityReferences(EntityGraphMapper.java:396)
at org.neo4j.ogm.context.EntityGraphMapper.mapEntity(EntityGraphMapper.java:230)
at org.neo4j.ogm.context.EntityGraphMapper.map(EntityGraphMapper.java:134)
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:83)
at org.neo4j.ogm.session.delegates.SaveDelegate.save(SaveDelegate.java:44)
at org.neo4j.ogm.session.Neo4jSession.save(Neo4jSession.java:419)
at sun.reflect.GeneratedMethodAccessor61.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:133)
at com.sun.proxy.$Proxy115.save(Unknown Source)
at org.springframework.data.neo4j.repository.support.SimpleGraphRepository.save(SimpleGraphRepository.java:70)
at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:503)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:488)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy128.save(Unknown Source)
at com.decisionwanted.domain.dao.decision.CharacteristicOptionDaoImpl.createOrUpdate(CharacteristicOptionDaoImpl.java:44)
at com.decisionwanted.domain.dao.decision.CharacteristicOptionDaoImpl.create(CharacteristicOptionDaoImpl.java:24)
at com.decisionwanted.domain.DecisionCharacteristicTest.testDecisionCharacteristicOptions(DecisionCharacteristicTest.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
My code:
#NodeEntity
public class Characteristic extends Authorable {
public final static String NODE_NAME = "Characteristic";
private final static String CONTAINS = "CONTAINS";
private final static String DEFINED_BY = "DEFINED_BY";
private String name;
private String description;
private Type type;
private Mode mode;
private boolean sortable;
#Relationship(type = CONTAINS, direction = Relationship.OUTGOING)
private Set<CharacteristicOption> options = new HashSet<>();
#Relationship(type = CONTAINS, direction = Relationship.INCOMING)
private CharacteristicGroup group;
#Relationship(type = DEFINED_BY, direction = Relationship.OUTGOING)
private Decision owner;
public Characteristic() {
}
public Characteristic(String name, String description, Type type, Mode mode, Decision owner, User author) {
this.name = name;
this.description = description;
this.type = type;
this.mode = mode;
this.owner = owner;
setAuthor(author);
}
public Characteristic(String name, String description, Type type, Mode mode, Decision owner, User author, CharacteristicGroup group) {
this(name, description, type, mode, owner, author);
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public boolean isSortable() {
return sortable;
}
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
public Set<CharacteristicOption> getOptions() {
return options;
}
public void setOptions(Set<CharacteristicOption> options) {
this.options = options;
}
public boolean addOption(CharacteristicOption option) {
return options.add(option);
}
public CharacteristicGroup getGroup() {
return group;
}
public void setGroup(CharacteristicGroup group) {
this.group = group;
}
public Decision getOwner() {
return owner;
}
public void setOwner(Decision owner) {
this.owner = owner;
}
public static enum Type {
//#formatter:off
BOOLEAN("Boolean"),
INTEGER("Integer"),
STRING("String");
//#formatter:on
private final String name;
Type(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static enum Mode {
//#formatter:off
CHECKBOX("CheckBox"),
SLIDER("Slider"),
SELECTBOX("SelectBox"),
RADIOGROUP("String");
//#formatter:on
private final String name;
Mode(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
#NodeEntity
public class CharacteristicOption extends BaseEntity {
private final static String CONTAINS = "CONTAINS";
private String name;
private String description;
private Object value;
#Relationship(type = CONTAINS, direction = Relationship.INCOMING)
private Characteristic characteristic;
public CharacteristicOption() {
}
public CharacteristicOption(String name, String description, Object value, Characteristic characteristic) {
this.name = name;
this.description = description;
this.value = value;
this.characteristic = characteristic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Characteristic getCharacteristic() {
return characteristic;
}
public void setCharacteristic(Characteristic characteristic) {
this.characteristic = characteristic;
}
}
#Override
public CharacteristicOption createOrUpdate(CharacteristicOption characteristicOption) {
auditing(characteristicOption);
return characteristicOptionRepository.save(characteristicOption);
}
What can be a reason of this issue and how to fix it ?
Your CharacteristicOption class declares a field:
private Object value;
A recent commit to the 2.1.0-SNAPSHOT excluded Object and Object[] references as persistable properties. As a result the OGM tried to map the value property via a relationship, rather than as a simple node attribute.
This has been corrected in the latest snapshot build.

Controller always receive null from json only a specify field

Hy folks!
First: I've found these posts before start my question here: questions/11344035 - questions/15939944 - questions/9412449 - questions/9162359 - questions/1551263.
Second: none of then solved my problem... :(
Well, this is my first MVC4 project, and i tryed send per $.ajax my data as follows:
var exames = {
"ExameId": "",
"Valor": "",
"CodLab": "",
"Dias": "",
"LayoutId": ""
};
var apoio = {
"ApoioId": "",
"Razao": "",
"Endereco": "",
"Bairro": "",
"Cidade": "",
"Uf": "",
"Cep": "",
"Telefone": "",
"Fax": "",
"Email": "",
"CodLab": "",
"Obs": "",
"Status": "",
"ArqRotina": "",
"ArqApoio": "",
"Senha": "",
"Exames": []
};
apoio.ApoioId = $("#hdApoioId").val();
apoio.Razao = $("#Razao").val();
apoio.Endereco = $("#Endereco").val();
apoio.Bairro = $("#Bairro").val();
apoio.Cidade = $("#Cidade").val();
apoio.Uf = $("#Uf").val();
apoio.Cep = $("#Cep").val();
apoio.Telefone = $("#Telefone").val();
apoio.Fax = $("#Fax").val();
apoio.Email = $("#Email").val();
apoio.CodLab = $("#CodLab").val();
apoio.Obs = $("#Obs").val();
apoio.Status = $("#Status").val();
apoio.ArqRotina = $("#ArquivoRotina").val();
apoio.ArqApoio = $("#ArquivoApoio").val();
apoio.Senha = $("#SenhaLab").val();
var tbody = document.getElementById(idTabExames).tBodies[0];
var numLinhas = tbody.rows.length;
for (var i = 0; i < numLinhas; i++) {
exames.ExameId = tbody.rows[i].cells[0].firstChild.nodeValue.toString();
exames.CodLab = tbody.rows[i].cells[1].firstChild.nodeValue;
exames.Dias = tbody.rows[i].cells[2].firstChild.nodeValue;
exames.Valor = tbody.rows[i].cells[3].firstChild.nodeValue;
exames.LayoutId = tbody.rows[i].cells[4].firstChild.nodeValue;
apoio.Exames.push(exames);
exames = {
"ExameId": "",
"CodLab": "",
"Dias": "",
"Valor": "",
"LayoutId": "",
"ApoioId": ""
};
}
$.ajax({
url: '/ApoioExames/Create',
data: JSON.stringify(apoio),
type: 'POST',
contentType: "application/json",
dataType: 'json',
processData: true,
success: function (result) {
if (result.Success == "1") {
if (console.window) console.log('sucess: '+result);
window.location.href = "/ApoioExames/Index";
}
else {
alert(xhr.status);
alert('Error: ' + xhr.responseText);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
Applying JSON.stringfy(apoio), I get a return of valid json (verified with http://jsonlint.com) but the apoio.Exames field (only it) is null on my controller. Always!
[HttpPost]
public JsonResult Create(ApoioModel apoio)
{
try
{
if (ModelState.IsValid)
{
if (apoio.Id > 0)
{
var exames = db.DbApoioExames.Where(p => p.ApoioId == apoio.Id);
foreach (ApoioExmModel exm in exames)
db.DbApoioExames.Remove(exm);
foreach (ApoioExmModel exm in exames)
db.DbApoioExames.Add(exm);
db.Entry(apoio).State = EntityState.Modified;
}
else
{
db.DbApoio.Add(apoio);
}
db.SaveChanges();
//If (Sucess== 1) { Salvar/Atualizar } else { Exception }
return Json(new { Success = 1, ApoioId = apoio.Id, ex = "" }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(new { Success = 0, ex = ex.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new { Success = 0, ex = new Exception("Impossível Salvar").Message }, JsonRequestBehavior.AllowGet);
}
My model ApoioModel and ApoioExmModel are:
[Table(name: "apoio", Schema = "public")]
public class ApoioModel
{
[Key, Column("id", Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("razao")]
[Display(Name = "Razão Social")]
[DataType(DataType.Html)]
[Required(ErrorMessage = "A razão social deve ser informada")]
public string Razao { get; set; }
[Display(Name = "Endereço")]
[Column("endereco")]
public string Endereco { get; set; }
[Display(Name = "Bairro")]
[Column("bairro")]
public string Bairro { get; set; }
[Display(Name = "Cidade")]
[Column("cidade")]
public string Cidade { get; set; }
[Display(Name = "CEP")]
[Column("cep")]
public string Cep { get; set; }
[Display(Name = "UF")]
[Column("uf")]
[StringLength(2)]
public string Uf { get; set; }
[Display(Name = "Status")]
[Range(0, 1), Column("status")]
public int Status { get; set; }
public virtual ICollection<ApoioExmModel> ApoiosExm { get; set; }
}
Table(name: "apoioexm", Schema = "public")]
public class ApoioExmModel
{
[Key, Column("id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
[Column("exame_id")]
public int ExameId { get; set; }
[Column("apoio_id")]
public int ApoioId { get; set; }
[Column("valor")]
public float Valor { get; set; }
[Column("codlab")]
public string CodLab { get; set; }
[Column("dias")]
public float Dias { get; set; }
[Column("layout_id")]
public int LayoutId { get; set; }
[ForeignKey("ApoioId")]
public virtual ApoioModel Apoios { get; set; }
}
I am trying create a CRUD master/detail. I am using Postgre, not SQL Server, but this is not the problem.
When I am debugging in Chrome, I view the data is transfering ok!
Request U R L : h t t p : / / l o c a l h o s t:9795/ApoioExames/Create
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/json
Origin:h t t p : / / localhost:9795
Referer: h t t p : / / localhost:9795/ApoioExames/Create
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
X-Requested-With:XMLHttpRequest
Request Payload
{Razao:kkkkkkk, Endereco:kkkkkkkkk, Bairro:kkkkkk, Cidade:kkkk, Uf:kk, Cep:12341234,…}
Bairro: "kkkkkk"
Cep: "12341234"
Cidade: "kkkk"
Endereco: "kkkkkkkkk"
Exames: [{ExameId:1252, Valor:1, CodLab:1, Dias:1, LayoutId:1826},…]
0: {ExameId:1252, Valor:1, CodLab:1, Dias:1, LayoutId:1826}
1: {ExameId:1252, CodLab:1, Dias:1, Valor:1, LayoutId:1826, ApoioId:}
Razao: "kkkkkkk"
Uf: "kk"
Someone help me?
Sorry my bad english and the large post!
Thanks!
I have two things in mind.
ApoiosExm should be named Exames or vice-versa
I'm not sure if it can map to a ICollection<ApoioExmModel>. Either way, if you ask me, I would recommend not mapping directly to your entity classes.

Resources