Este artigo analisa três maneiras de analisar o JSON com base no Java. Compartilhe -o para sua referência, como segue:
1. O que é JSON?
JSON é uma estrutura de dados que substitui o XML. Comparado com o XML, é menor, mas possui bons recursos de descrição. Devido à sua pequenez, a rede transmite dados para reduzir mais tráfego e acelerar.
JSON é uma série de cordas, mas os elementos são marcados com símbolos específicos.
{} Colchetes duplos representam objetos
[] Suportes representam a matriz
"" Em citações duplas são atributos ou valores
: O cólon indica que o último é o valor do primeiro (esse valor pode ser uma string, um número ou outra matriz ou objeto)
Então {"Nome": "Michael"} pode ser entendido como um objeto que contém o nome como Michael
E [{"Name": "Michael"}, {"Nome": "Jerry"}] significa uma matriz contendo dois objetos
Claro, você também pode usar {"Name": ["Michael", "Jerry"]} para simplificar o acima, que é um objeto com uma variedade de nomes.
2. Análise tradicional de JSON: JSON Analysis
1. Gere String JSON
public static string createjSonstring (chave de string, valor do objeto) {jsonObject jsonObject = new jsonObject (); jsonObject.put (chave, valor); retornar jsonObject.toString ();}2. Analisando as cordas JSON
É dividido nas três situações a seguir: um javabeu, uma matriz de listas e uma matriz de listas com mapa aninhado:
importar java.util.ArrayList; importar java.util.hashmap; importar java.util.iterator; importar java.util.list; importar java.util.map; importar**** ^, import.JsonOnSon.JsonArray; import org.json.jsonObject; import.android.myjson.anstray; Data.json.json.jsonObject; import.android.myjson.anstray; importrg.json.jsonObject; import.android.myjson.anstray; classe JSontools {public static pessoa getPerson (chave de string, string jSonstring) {pessoa pessoa = new Person (); tente {jsonObject jsonObject = new JsonObject (JSonstring); JsonObject Persobject = JsonObject.getjsonObject ("Pessoa"); pessoa.setId (Persobject.getInt ("ID")); pessoa.SetName (personobject.getString ("nome")); pessoa.SetAddress (Persobject.getString ("endereço")); } catch (Exceção e) {// TODO: manipular a exceção} Return Pessoa; } Lista estática pública getPersons (chave de string, string jSonstring) {list list = new ArrayList (); tente {jsonObject jsonObject = new JsonObject (JSonstring); // retorna a matriz de json jsonArray jsonArray = jsonObject.getjsonArray (key); for (int i = 0; i <jsonArray.length (); i ++) {jsonObject jsonObject2 = jsonArray.getjsonObject (i); Pessoa pessoa = nova pessoa (); pessoa.setId (jsonObject2.getInt ("id")); pessoa.SetName (jsonObject2.getString ("nome")); pessoa.setAddress (jsonObject2.getString ("endereço")); list.add (pessoa); }} Catch (Exceção e) {// TODO: lide a Lista de retorno da exceção}; } Lista estática pública getList (tecla String, string jSonstring) {list list = new ArrayList (); tente {jsonObject jsonObject = new JsonObject (JSonstring); JsonArray jsonArray = jsonObject.getjsonArray (key); for (int i = 0; i <jsonArray.length (); i ++) {string msg = jsonArray.getString (i); list.add (msg); }} Catch (Exceção e) {// TODO: lide a Lista de retorno da exceção}; } Lista estática pública> ListkeyMaps (chave de string, string jSonstring) {list> list = new ArrayList> (); tente {jsonObject jsonObject = new JsonObject (JSonstring); JsonArray jsonArray = jsonObject.getjsonArray (key); for (int i = 0; i <jsonArray.length (); i ++) {jsonObject jsonObject2 = jsonArray.getjsonObject (i); Mapa mapa = new hashmap (); Iterator iterator = jsonObject2.keys (); while (iterator.hasnext ()) {string json_key = iterator.Next (); Objeto json_value = jsonObject2.get (json_key); if (json_value == null) {json_value = ""; } map.put (json_key, json_value); } list.add (mapa); }} Catch (Exceção e) {// TODO: lide a Lista de retorno da exceção}; }}3. Análise GSON de JSON
1. Gere String JSON
importar com.google.gson.gson; public class jsonutils {public static string createjsonObject (objeto obj) {gson gson = new gson (); String str = gson.tojson (obj); retornar str; }}2. Analise JSON
importar java.util.ArrayList; importar java.util.list; importar java.util.map; importar com.google.gson.gson; importar com.google.gson.reflect.typetken; @param cls * @return */ public static t getperson (string jSonstring, classe cls) {t t = null; tente {gson gson = new gson (); t = gson.Fromjson (JSonstring, CLS); } catch (Exceção e) {// TODO: lidar com exceção} retornar t; } / ** * Use GSON para analisar a lista * * @param * @param jSonstring * @param cls * @return * / list public static getPersons (string jSonstring, classe cls) {list list = new ArrayList (); tente {gson gson = new gson (); list = gson.fromjson (JSonstring, new TypeToken> () {} .getType ()); } catch (Exceção e) {} Lista de retorno; } / ** * @param jSonstring * @return * / list public static getList (string jSonstring) {list list = new ArrayList (); tente {gson gson = new gson (); list = gson.fromjson (JSonstring, new TypeToken> () {} .getType ()); } catch (Exceção e) {// TODO: HOLANDE Exceção} Lista de retorno; } Lista estática pública> ListkeyMaps (String jSonstring) {list> list = new ArrayList> (); tente {gson gson = new gson (); list = gson.Fromjson (JSonstring, new TypeToken >> () {} .getType ()); } catch (Exceção e) {// TODO: HOLANDE Exceção} Lista de retorno; }}4. Fastjson analisando
importar java.util.ArrayList; importar java.util.list; importar java.util.map; importar com.alibaba.fastjson.json; importar com.alibaba.fastjson.typereference; classe pública JSontool {public tactPerson (string jSonstring, class). tente {t = json.parseObject (jSonstring, cls); } catch (Exceção e) {// TODO: lidar com exceção} retornar t; } Lista estática pública getPersonList (String jSonstring, classe cls) {list list = new ArrayList (); tente {list = json.parsearray (jSonstring, cls); } catch (Exceção e) {// TODO: HOLANDE Exceção} Lista de retorno; } Lista estática pública> getPersonListMap1 (String jSonstring) {list> list = new ArrayList> (); tente {list = json.parseObject (jSonstring, new TypeReference >> () {} .getType ()); } catch (Exceção e) {// TODO: HOLANDE Exceção} Lista de retorno; }}Resumir:
Para dispositivos móveis, especialmente no caso de um ambiente ruim de rede e limitações de tráfego, o JSON economizará tráfego e terá maior eficiência de transmissão em comparação com a transmissão de dados do formato XML. Entre esses três métodos analíticos, o Fastjson é o mais eficiente e é recomendado.
PS: Em relação à operação JSON, aqui estão algumas ferramentas on -line práticas do JSON para sua referência: Ferramentas on -line de código JSON, inspeção, embelezamento e formatação: Ferramenta de formatação online JSON : Ferramenta de conversão mútua xml/json online: Código JSON Formatação/embelezamento on -line/Ferramentas de compressão/edição/conversão: Ferramentas de compactação/fuga JSON on -line: C estilo de idioma/html/css/json formatação e ferramentas de embelezamento:
http://tools.vevb.com/code/json
http://tools.vevb.com/code/jsonformat
http://tools.vevb.com/code/xmljson
http://tools.vevb.com/code/jsonncodeFormat
http://tools.vevb.com/code/json_yasuo_trans
http://tools.vevb.com/code/ccode_html_css_json
Espero que este artigo seja útil para a programação Java de todos.