첫째 .. 저는 JSON.NET이나 다른 파서에 관심이 없습니다. DataContractJsonSerializer 만
REST API로 가져 와서 보내는 구조로 작업해야하며 다음과 같이 보입니다.
{ "records": [
{
"attributes": {
"OBJECTID": 1,
"Address": "380 New York St.",
"City": "Redlands",
"Region": "CA",
"Postal": "92373"
}
},
{
"attributes": {
"OBJECTID": 2,
"Address": "1 World Way",
"City": "Los Angeles",
"Region": "CA",
"Postal": "90045"
}
}
]
우리가 볼 수있는 것은 다음과 같습니다.
class SomeData
{
public List<SomeRecord> Records { get; set; }
}
class SomeRecord
{
public List<KeyValuePair<string, string>> Attributes { get; set; }
}
serializer가 이와 같은 구조를 생성 할 수 있도록 객체를 어떻게 어트 리뷰 션합니까? 아니면 각 속성을 포함하는 속성을 가진 객체를 만들어야합니까?
문제는이 웹 서비스가 여기저기서 속성 인 것처럼 보이며 가능한 모든 이름조차 확신하지 못합니다. 따라서 KVP 목록은 좋은 선택처럼 보이지만 저에게는 작동하지 않습니다.
다음이 작동해야합니다.
[DataContract]
[KnownType(typeof(Record))]
public class RecordList
{
public RecordList()
{
Records = new List<Record>();
}
[DataMember]
public List<Record> Records { get; set; }
}
public class Record
{
public Record()
{
Attributes = new AttributeList();
}
[DataMember]
public AttributeList Attributes { get; set; }
}
[Serializable]
public class AttributeList : DynamicObject, ISerializable
{
private readonly Dictionary<string, object> attributes = new Dictionary<string, object>();
public override bool TrySetMember(SetMemberBinder binder, object value)
{
attributes[binder.Name] = value;
return true;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var kvp in attributes)
{
info.AddValue(kvp.Key, kvp.Value);
}
}
}
[Test]
public void TestSerialize()
{
var holder = new RecordList();
dynamic record = new Record();
record.Attributes.OBJECTID = 1;
record.Attributes.Address = "380 New York St.";
record.Attributes.City = "Redlands";
record.Attributes.Address = "Region";
record.Attributes.Region = "CA";
record.Attributes.Postal = "92373";
holder.Records.Add(record);
var stream1 = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(RecordList));
serializer.WriteObject(stream1, holder);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of holder object: ");
Console.WriteLine(sr.ReadToEnd());
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다