比方說,我有一個文件sample.json
,其中包含一個如下所示的對象數組。使用Streaming API和Json解析器進行JSON解析 - 混合模式
[ {Name: "ABC", "email" : "[email protected]", "city" : "NewYork"}, {Name: "XYZ", "email" : "[email protected]", "city" : "NewJersey"}]
我正在使用TestNG框架和GSON庫來解析JSON。
下面是我想要解析JSON對象的類。我的目標是通過數組中的名稱過濾對象並僅返回該對象。 我正在使用Streaming API來避免一次出現在json文件中的所有數據。
public class JSON{
private JsonObject jsonObject;
@Test
public void readJSON(){
getJSONObject("C:\\..\\sample.json", "ABC");
readData("email");
}
public JsonObject getJSONObject(fileName, Name){
JsonReader jsonReader = new JsonReader(new FileReader(fileName));
jsonReader.beginArray();
while (jsonReader.hasNext()){
str = jsonReader.nextString();
If (str.equals(Name)){
System.out.println("Found Name");
// To get the object - we can use fromJson(jsonReader, Person.class),
// where Person.class defines all the json variables as class variables.
// But I want to use JsonParser or something like that to return just this object which has the Name "ABC"
}
}
} }
原因,我不希望創建一個Person類,並使用fromJSON因爲我使用此功能對不同類型的JSON字符串。所以我不喜歡爲不同的字符串創建不同的類。我想使用其他的東西,只是返回所需的對象。另外我不確定如何使用Streaming API方法的hasNext()遍歷數組來查找所需的對象。
任何輸入讚賞。謝謝。
http://stackoverflow.com/questions/23698415/how-to-filter-json-array-in-c-sharp – Nothing