[c#] .net에서 json 구문 분석에 대한 도움말
Have you tried using Json.NET? You can find an example on this previous SO post.
-------------------If you are able to change that JSON then I would go with James' answer but if it turns out tat you can't things will get more complicated. I wasn't able to find a JSON serialiser that would understand that format with the index numbers in the JSON as property names. It does however appear to be valid and is well understood by all of the browsers I tried.
I think your best option here is to use a Javascript library for .net (there are a couple of these but I like IronJS). Using this you can just execute the JSON and read out the result. Here is some sample code that reads your JSON from a file and writes the results to the console.
public class Place
{
public int ID { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var ctx = new IronJS.Hosting.CSharp.Context();
string json;
using (TextReader reader = File.OpenText("array_items.txt"))
{
json = reader.ReadToEnd();
}
CommonObject result= (CommonObject)ctx.Execute("var x=" + json);
Dictionary<uint,BoxedValue> indexes = new Dictionary<uint,BoxedValue>();
result.GetAllIndexProperties(indexes, uint.MaxValue);
List<Place> places = new List<Place>();
foreach (uint idx in indexes.Keys)
{
Place p = new Place();
p.ID = (int)idx;
p.Name = (string)indexes[idx].Object.Members["Name"];
p.Latitude = (double)indexes[idx].Object.Members["Latitude"];
p.Longitude = (double)indexes[idx].Object.Members["Longitude"];
places.Add(p);
}
foreach (Place place in places)
{
Console.WriteLine("ID = {0}", place.ID);
Console.WriteLine("Name = {0}", place.Name);
Console.WriteLine("Latitude = {0}", place.Latitude);
Console.WriteLine("Longitude = {0}", place.Longitude);
}
Console.ReadKey();
}
}
그러나 여기서주의해야합니다. 실행중인 위치에 따라 스크립트 삽입 공격에 노출 될 수 있습니다. 잠재적으로 유해한 스크립트 (예 : 숫자의 일부가 아니고 따옴표 안에없는 콘텐츠)에 대해 JS를 스캔하는 것이 가장 좋습니다.
-------------------안녕하세요, JSON을 변경할 수 없다면 다음을 수행하여 역 직렬화 할 수 있습니다.
var serializer = new JavaScriptSerializer();
var deserializedDictionary = serializer.Deserialize<Dictionary<string, PlaceDetails>>(jsonString);
var result = new List<Place>();
foreach (var key in deserializedDictionary.Keys)
{
result.Add(new Place(key, deserializedDictionary[key]));
}
필수 수업 :
public class PlaceDetails
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public string Name { get; set; }
}
public class Place
{
public Place(string placeID, PlaceDetails placeDetails)
{
this.PlaceID = Convert.ToInt32(placeID);
this.Latitude = placeDetails.Latitude;
this.Longitude = placeDetails.Longitude;
this.Name = placeDetails.Name;
}
public int PlaceID { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public string Name { get; set; }
}
System.Web.Extensions.dll에 대한 참조 와 System.Web.Script.Serialization
네임 스페이스 사용 이 여전히 필요합니다 .
도움이 되었기를 바랍니다.
-------------------desearilzation을 시도하십시오. 도움이 될만한 게시물은 다음과 같습니다.
JSON의 C # 자동 속성 역 직렬화
C #에서 JSON 구문 분석
-------------------JSON 형식을 다음과 같이 변경하겠습니다.
[
{
"PlaceID" : 1,
"Latitude" :52.1643540,
"Longitude" :-2.154353,
"Name" :"AAA"
},
{
"PlaceID" : 2,
"Latitude":53.13,
"Longitude":-2.13445,
"Name":"BBB"
},
{
"PlaceID" : 3,
"Latitude":55.143243,
"Longitude":-2.45234,
"Name":"CCC"
}
]
그런 다음 다음을 사용합니다.
public class Place
{
public int PlaceID { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public string Name { get; set; }
}
deserialize하려면 다음을 사용합니다.
JavaScriptSerializer serializer = new JavaScriptSerializer();
var listOfPlaces = serializer.Deserialize<List<Place>>(jsonString);
JavaScriptSerializer를 사용하려면 System.Web.Extensions.dll에 대한 참조 와 System.Web.Script.Serialization
네임 스페이스 를 사용해야합니다 .
다음과 같이 했습니까?
public class Place
{
public string ID { get; set; }
public string Name { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
}
private void Run()
{
List<Place> places = new List<Place>();
JObject jObject = JObject.Parse(json);
foreach (var item in jObject)
{
JToken jPlace = jObject[item.Key];
float latitude = (float)jPlace["Latitude"];
float longitude = (float)jPlace["Longitude"];
string name = (string)jPlace["Name"];
places.Add(new Place { ID = item.Key, Name = name, Latitude = latitude, Longitude = longitude });
}
}
출처
https://stackoverflow.com/questions/7415155