⑴ json和xml數據的解析方式
《2.1》首先創建一個 json文件吵塌,eg: Student.json
《2.2》 定義一個model類 StuJsonModel
四、總結,個人認為三方固然好用,節省了開發時間,但是一旦出問題,還是需要比較久的時間去處理bug. 在使用JSONKit的時候,因為創建的json文升舉圓件最後一個數組後面多了一個 「,」逗號,JSONKit就不能解析了,為nil。而系統的就可以解析。所以做開發還是要細心、細心答升、細心!!! 重要的事情說3遍!!!歡迎交流
傳送門 http://code.cocoachina.com/view/134937
⑵ 怎麼生成和解析iOS開發JSON格式數據
導語:JSON作為數據包格式傳輸的時候具有更高的效率,這是因為JSON不像XML那樣需要有嚴格的閉合標簽,這就讓有效數據量與總數據包比大大提升,從而減少同等數據流量的情況下,網路的傳輸壓力。JSON 可以將 javaScript 對象中表示的一組數據轉換為字元串,然後就可以在函數之間輕松地傳遞這個字元串,或者在非同步應用程序中將字元串從 Web 客戶機傳遞給伺服器端程序。這個字元串看起來有點兒古怪,但是JavaScript很容易解釋它,而且 JSON 可以表示比"名稱 / 值對"更復雜的結構。例如,可以表示數組和復雜的對象,而不僅僅是鍵和值的簡單列表。
一、如何生成JSON格式的'數據?
1、利用字典NSDictionary轉換為鍵/值格式的數據。
// 如果數組或者字典中存儲了 NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他對象,就不能直接保存成文件了.也不能序列化成 JSON 數據.
NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
// 1.判斷當前對象是否能夠轉換成JSON數據.
// YES if obj can be converted to JSON data, otherwise NO
BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
if (isYes) {
NSLog(@"可以轉換");
/* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8.
*/
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
/*
Writes the bytes in the receiver to the file specified by a given path.
YES if the operation succeeds, otherwise NO
*/
// 將JSON數據寫成文件
// 文件添加後綴名: 告訴別人當前文件的類型.
// 注意: AFN是通過文件類型來確定數據類型的!如果不添加類型,有可能識別不了! 自己最好添加文件類型.
[jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"JSON數據生成失敗,請檢查數據格式");
}
2、通過JSON序列化可以轉換數組,但轉換結果不是標准化的JSON格式。
NSArray *array = @[@"qn", @18, @"ya", @"wj"];
BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
if (isYes) {
NSLog(@"可以轉換");
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
[data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
} else {
NSLog(@"JSON數據生成失敗,請檢查數據格式");
}
二、如何解析JSON格式的數據?
1、使用TouchJSon解析方法:(需導入包:#import "TouchJson/JSON/CJSONDeserializer.h")
//使用TouchJson來解析北京的天氣
//獲取API介面
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];
//定義一個NSError對象,用於捕獲錯誤信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"jsonString--->%@",jsonString);
//將解析得到的內容存放字典中,編碼格式為UTF8,防止取值的時候發生亂碼
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
//因為返回的Json文件有兩層,去第二層內容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);
//取值列印
NSLog(@"%@",[NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
2、使用SBJson解析方法:(需導入包:#import "SBJson/SBJson.h")
//使用SBJson解析北京的天氣
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"%@", [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
3、使用IOS5自帶解析類NSJSONSerialization方法解析:(無需導入包,IOS5支持,低版本IOS不支持)
// 從中國天氣預報網請求數據
NSURL *url = [ NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
// 創建請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 在網路完成的 Block 回調中,要增加錯誤機制.
// 失敗機制處理: 錯誤的狀態碼!
// 最簡單的錯誤處理機制:
if (data && !error) {
// JSON格式轉換成字典,IOS5中自帶解析類NSJSONSerialization從response中解析出數據放到字典中
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSDictionary *dict = obj[@"weatherinfo"];
NSLog(@"%@---%@", dict, dict[@"city"]);
}
}] resume];
4、使用JSONKit的解析方法:(需導入包:#import "JSONKit/JSONKit.h")
//如果json是“單層”的,即value都是字元串、數字,可以使用objectFromJSONString
NSString *json1 = @"{"a":123, "b":"abc"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
//如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能會報錯(測試結果表明:使用由網路或得到的php/json_encode生成的json時會報錯,但使用NSString定義的json字元串時,解析成功),最好使用:
NSString *json2 = @"{"a":123, "b":"abc", "c":[456, "hello"], "d":{"name":"張三", "age":"32"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 :JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
⑶ class<t>類型的json怎麼解析
一、 JSON (JavaScript Object Notation)一種簡單的數據格式,比xml更輕巧。
Json建構於兩種結構:
1、「名稱/值」對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。 如:
{
「name」:」jackson」,
「age」:100
}
2、值的有序列表(An ordered list of values)。在大部分語言中,它被理解為鬧歲並數組(array)如:
{
「students」:
[
{「name」:」jackson」,「age」:100},
{「name」:」michael」,」age」:51}
]
}
二、java解析JSON步驟
A、伺服器端將數據轉換成json字元串
首先、伺服器端項目要導入json的jar包和json所依賴的jar包至builtPath路徑下(這些可以到JSON-lib官網下載:http://json-lib.sourceforge.net/)
然後將數據轉液跡為json字元串,核心函數是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客戶端將json字元串轉換為相應的javaBean
1、客雀御戶端獲取json字元串(因為android項目中已經集成了json的jar包所以這里無需導入)
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 獲取HttpURLConnection連接對象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 設置連接屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 獲取相應碼
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相當於內存輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 將輸入流轉移到內存輸出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 將內存流轉換為字元串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、獲取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 將json字元串轉換為json對象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONObject personObj = jsonObj.getJSONObject("person");
// 獲取之對象的所有屬性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return person;
}
public static List<Person> getPersons(String jsonStr)
{
List<Person> list = new ArrayList<Person>();
JSONObject jsonObj;
try
{// 將json字元串轉換為json對象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍歷jsonArray
for (int i = 0; i < personList.length(); i++)
{
// 獲取每一個json對象
JSONObject jsonItem = personList.getJSONObject(i);
// 獲取每一個json對象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
⑷ 如何解析這個的JSON 文件
1、添加dll
2、string的串傳入序列化成json就行了
前端會自動解析json的
C# code?
#region
//MemcachedClient mc = new MemcachedClient();
string test = "{a, b}";
#endregion
protected void Page_Load(object sender, EventArgs e)
{
// log4net.ILog log = log4net.LogManager.GetLogger("log");
ReturnJsonString(test);
}
public string ReturnJsonString(string test)
{
if (test.Length <= 0) return "[]";
return JsonConvert.SerializeObject(test).ToString();
}
⑸ Golang解析json的特殊情況處理
Go解析json遇到了大數字、不定格式等特殊情況,在此做了一個整理。
選擇哪個要視輸入而定。
json.Unmarshal 操作對象是一個 []byte ,也就意味著被處理的JSON要全部載入到內存。如果有一個載入完的JSON使用 json.Unmarshal 會快一些。
json.Decoder 操作的是一個 stream ,或者其他實現了 io.Reader 介面的類型。意味著可以在接收或傳輸的同時對其進行解析。當處理一組較大數據時無需重新整個JSON到內存中。
最好的選擇辦法如下:
默認情況下,go對json解析過程中遇到的數字都會當做float64處理。如果數字過大會有精度丟失。可以使用json.Number來處理。
輸出結果:
使用 json.Decoder 只能操作 io.Reader 類型的JSON數據。
有時候遇到欄位不定的JSON,需要一邊判斷一邊解析。如:
可以先統一解組到interface{} 然後判斷關鍵欄位再進行後續處理。
結果
使用RawMessage便於分步Unmarshal
原文鏈接
⑹ 如何java解析json數組
packagejava_email.demo;
importcom.google.gson.JsonArray;
importcom.google.gson.JsonObject;
importcom.google.gson.JsonParser;
publicclassReadJSON{
publicstaticvoidmain(Stringargs[]){
JsonParserparser=newJsonParser();//創建JSON解析器
Stringjson="{"title":"創建語音","content":[{"labels":["很好看","很好吃"],"voiceUrl":"/voice/1323423.pcm","voiceText":"很好","createDate":"2018-06-1114:29:43"},{"labels":["很好看1","很好吃"],"voiceUrl":"/voice/1323423.pcm","voiceText":"很好","createDate":"2018-07-2614:30:43"}],"enterpriseId":"20180726"}";
JsonObjectobject=(JsonObject)parser.parse(json);//創建JsonObject對象
System.out.println("title="+object.get("title"));//
System.out.println("enterpriseId="+object.get("enterpriseId"));
JsonArrayarray=object.get("content").getAsJsonArray();//得到為json的數組
System.out.println("content="+array);
for(inti=0;i<array.size();i++){
JsonObjectsubObject=array.get(i).getAsJsonObject();
System.out.println("labels="+subObject.get("labels"));
System.out.println("createDate="+subObject.get("createDate"));
}
}
}