Deserialize 할 때 json에서 k__BackingField를 제거하는 방법
xml 파일을 .net C # 개체로 직렬화 한 후 반환 된 json에서 k_BackingField를 얻습니다.
.net C # 개체에 DataContract 및 DataMember 특성을 추가했지만 json, 클라이언트 쪽에서는 아무것도 얻지 못합니다.
[XmlRoot("person")]
[Serializable]
public class LinkedIn
{
[XmlElement("id")]
public string ID { get; set; }
[XmlElement("industry")]
public string Industry { get; set; }
[XmlElement("first-name")]
public string FirstName { get; set; }
[XmlElement("last-name")]
public string LastName { get; set; }
[XmlElement("headline")]
}
반환 된 json의 예 :
home: Object
<FirstName>k__BackingField: "Storefront"
<LastName>k__BackingField: "Doors"
클래스를 직렬화에 사용할 수있는 경우 자동 속성 구문은 실제로 권장되지 않습니다. 백업 필드가되는 이유는 코드가 컴파일 될 때마다 다를 수있는 컴파일러에 의해 생성됩니다. 이로 인해 클래스가 변경되지 않은 경우에도 비 호환성 문제가 발생할 수 있습니다 (코드를 다시 컴파일하기 만하면 됨).
이 경우 DataMember 속성을 적용하면 문제가 해결 될 것이라고 생각합니다. 그러나 클래스를 직렬화에 사용해야하는 경우 전체 속성 구문을 사용하는 것이 좋습니다.
[Serializable]
수업에서 제거
기본 WebApi serializer는 "__BackingField :"구문을 c # 자동 속성에 추가합니다. App_Start의 WebConfig에 이것을 추가하여 찾고있을 수있는 깔끔한 json을 얻으십시오.
using Newtonsoft.Json;
...
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
[Serializable]
전통적인 방법을 사용하여 직렬화 할 수 있도록 표시된 일부 객체가 있지만 Web API와 함께 사용하려면 JSON으로 명확하게 직렬화해야합니다. 로 설정 IgnoreSerializableAttribute
하면 true
Newtonsoft.Json이 Microsoft의 직렬화 기처럼 작동하지 않고 대신 공용 속성을 직렬화합니다.
TLDR : WebApiConfig.cs에 다음을 추가하십시오.
((Newtonsoft.Json.Serialization.DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
중재자 : 여러 번 질문 한 질문에 대해 정말 좋은 답변을 삭제하는 대신 중복 질문을 삭제하십시오. 이것은 유효한 질문에 대한 유효한 대답입니다.
데이터를 노출하는 간단하고 쉬운 방법 우리는 객체의 데이터를 읽기 쉽고 일관된 형식으로 노출해야합니다.
먼저 [Serializable] 제거
[Serializable]
이제 아래 예제와 같이 클래스 에 [DataContract] 를 추가 하고 속성에 [DataMember] 를 추가합니다.
[DataContract]
public class UserDiscretion : UserReport
{
[DataMember]
public String DiscretionCode { get; set; }
public String DiscretionDescription { get; set; }
}
이 도움말 희망
감사합니다.
몇 가지 옵션 :
[Serializable]
모델에서 제거추가
[DataContract]
및[DataMember]
함께 모델에[Serializable]
아래 줄 추가
App_Start/WebApiConfig.cs
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
JSON.NET의 경우 도움이 될 수있는 또 다른 솔루션입니다. [Newtonsoft.Json.JsonObject] 속성으로 클래스를 표시하는 것으로 충분할 수 있습니다.
I was working with cs classes built from xsd and was adding some properties using partial classes. After json serialization these properties were marked with k_BackingField. JsonFormatter settings mentioned in other answers helped as well, but more simple was to mark partial class with [JsonObject] attribute.
I was using DataContractJsonSerializer
with a class from another assembly that had the Serializable
attribute. The output contained "k__BackingField". Removing the Serializable
attribute (in the other assembly) fixed this. Not sure why.
Assuming you see this issue inside of your MVC project, I've found that it's pretty simple to replace the use of @Html.JsonData. Here is a snippet of code that has worked for me in the past:
<input type="hidden" id="Model" value="@Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model))" />
Not as elegant, but simple in a pinch.
I had this issue when I have self reference properties in my class such as;
class Person {
List<Person> Friends { get; set;}
}
And there was a result, the person was friend with himself. I just made sure there was no self referencing objects in my result set. Hope this helps.
I had to use the [Serializable] attributes, so removing it was not an option.
XmlSerializer ignores [XmlAttribute] in WebApi
The above resolution solved it for me.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
in my case this error was for the Newtonsoft.Json Version, the server looked for 6.0.0 version and I had the 11.0, so I had to install the version 6.0.0
Friends, don't declare properties like this:
public String DiscretionCode { get; set; }
public String DiscretionDescription { get; set; }
But, create auxiliar vars, like old....
private String discretionCode;
public String DiscretionCode
{
get { return discretionCode;}
set { discretionCode = value; }
}
참고URL : https://stackoverflow.com/questions/13022198/how-to-remove-k-backingfield-from-json-when-deserialize
'development' 카테고리의 다른 글
Selenium WebDriver : JavaScript가있는 복잡한 페이지가로드 될 때까지 기다립니다. (0) | 2020.08.30 |
---|---|
CSS 테두리가 1px 미만 (0) | 2020.08.30 |
NeatBeans IDE에서 글꼴 크기를 늘리는 방법은 무엇입니까? (0) | 2020.08.29 |
jquery를 사용하여 범위에서 텍스트 가져 오기 (0) | 2020.08.29 |
라디안 대신 각도를 사용하기 위해 sin, cos 및 tan을 어떻게 얻을 수 있습니까? (0) | 2020.08.29 |