Este artículo analiza tres formas de analizar JSON basados en Java. Compártelo para su referencia, como sigue:
1. ¿Qué es JSON?
JSON es una estructura de datos que reemplaza a XML. En comparación con XML, es más pequeño pero tiene buenas capacidades de descripción. Debido a su pequeñez, la red transmite datos para reducir más tráfico y acelerar.
JSON es una cadena de cadenas, pero los elementos están marcados con símbolos específicos.
{} Los soportes dobles representan objetos
[] Los soportes representan una matriz
"" En las cotizaciones dobles hay atributos o valores
: El colon indica que el último es el valor del primero (este valor puede ser una cadena, un número u otra matriz u objeto)
Entonces {"Nombre": "Michael"} puede entenderse como un objeto que contiene el nombre como Michael
Y [{"nombre": "Michael"}, {"Nombre": "Jerry"}] significa una matriz que contiene dos objetos
Por supuesto, también puede usar {"Nombre": ["Michael", "Jerry"]} para simplificar lo anterior, que es un objeto con una matriz de nombres.
2. Análisis tradicional de JSON: análisis JSON
1. Generar cadena JSON
public static string createJSonstring (clave de cadena, valor de objeto) {jsonObject jsonObject = new jsonObject (); jsonObject.put (clave, valor); return jsonObject.ToString ();}2. Poner las cuerdas JSON
Se divide en las siguientes tres situaciones: un Javabean, una matriz de lista y una matriz de lista con mapa anidado:
import java.util.arrayList; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import org.json.jsonArray; import org.json.jsonObject; import Com.android.myjson.domain.person;/*** Complete The Parsing of the Parsing of the Parsing of the Parsing of the Parsing of the**/the**/datsing the parsing de parsing de parsing; JSONTOOLS {Public static Person Getperson (clave de cadena, string jsonstring) {persona persona = nueva persona (); intente {jsonObject jsonObject = new JsonObject (jsonstring); JsonObject PersonObject = jsonObject.getJsonObject ("persona"); Person.setId (PersonObject.GetInt ("id")); persona.setName (PersonObject.getString ("Nombre")); persona.setaddress (personaObject.getString ("dirección")); } catch (Exception e) {// tODO: manejar excepción} persona de retorno; } public static list getPersons (clave de cadena, cadena jsonstring) {list list = new ArrayList (); intente {jsonObject jsonObject = new JsonObject (jsonstring); // Devuelve la matriz de JSON JSONArray JSONArray = jsonObject.getJsonArray (Key); for (int i = 0; i <jsonArray.length (); i ++) {jsonObject jsonObject2 = jsonArray.getJsonObject (i); Persona persona = nueva persona (); persona.setId (jsonObject2.getInt ("id")); persona.setName (jsonObject2.getString ("nombre")); persona.setaddress (jsonObject2.getString ("dirección")); list.add (persona); }} catch (Exception e) {// tODO: manejar excepción} lista de retorno; } public static list getList (clave de cadena, cadena jsonstring) {list list = new ArrayList (); intente {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 (Exception e) {// tODO: manejar excepción} lista de retorno; } public static list> listkeyMaps (clave de cadena, cadena jsonstring) {list> list = new ArrayList> (); intente {jsonObject jsonObject = new JsonObject (jsonstring); JSONArray JSONArray = jsonObject.getJsonArray (Key); for (int i = 0; i <jsonArray.length (); i ++) {jsonObject jsonObject2 = jsonArray.getJsonObject (i); Mapa map = nuevo hashmap (); Iterador 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 (Exception e) {// tODO: manejar excepción} lista de retorno; }}3. Análisis GSON de JSON
1. Generar cadena JSON
import com.google.gson.gson; public class jsonutils {public static string createjsonObject (object obj) {gson gson = new Gson (); Cadena str = gson.tojson (obj); regresar str; }}2. Analizar JSON
import java.util.arrayList; import java.util.list; import java.util.map; import com.google.gson.gson; import com.google.gson.reflect.typetoken ;; public class gsonTools {public gsonTools () {// ado @param cls * @return */ public static t getperson (string jsonstring, class cls) {t t = null; intente {gson gson = new Gson (); t = gson.fromjson (jsonstring, cls); } catch (Exception e) {// tODO: manejar excepción} return t; } / ** * Use la lista GSON para analizar * * @param * @param jsonstring * @param cls * @return * / public static list getPersons (string jsonstring, class cls) {list list = new ArrayList (); intente {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken> () {} .gettype ()); } catch (excepción e) {} Lista de retorno; } / ** * @param jsonstring * @return * / public static list getList (string jsonstring) {list list = new ArrayList (); intente {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken> () {} .gettype ()); } catch (Exception e) {// tODO: manejar excepción} lista de retorno; } public static list> listkeyMaps (string jsonstring) {list> list = new ArrayList> (); intente {gson gson = new Gson (); list = gson.fromjson (jsonstring, new typetoken >> () {} .gettype ()); } catch (Exception e) {// tODO: manejar excepción} lista de retorno; }}4. Fastjson analizador
import java.util.arrayList; import java.util.list; import java.util.map; import com.alibaba.fastjson.json; import com.alibaba.fastjson.tyPereference; public class JSontool {public static t getperson (string jsonstring, class cls) {t t = null; intente {t = json.parseObject (jsonstring, cls); } catch (Exception e) {// tODO: manejar excepción} return t; } public static List getPersonList (String jsonstring, class cls) {list list = new ArrayList (); intente {list = json.parsearray (jsonstring, cls); } catch (Exception e) {// tODO: manejar excepción} lista de retorno; } Lista de estática pública> getPersonListMap1 (string jsonstring) {list> list = new ArrayList> (); intente {list = json.parseObject (jsonstring, new typereference >> () {} .gettype ()); } catch (Exception e) {// tODO: manejar excepción} lista de retorno; }}Resumir:
Para los dispositivos móviles, especialmente en el caso del entorno de red deficiente y las limitaciones de tráfico, JSON ahorrará tráfico y tendrá una mayor eficiencia de transmisión en comparación con la transmisión de datos de formato XML. Entre estos tres métodos analíticos, FastJson es el más eficiente y se recomienda.
PD: Con respecto a la operación JSON, aquí hay algunas herramientas prácticas en línea de JSON para su referencia: VERIFICACIÓN DE CÓDIGO JSON, INSPECCIÓN, BABÍA DE HERRAMIENTAS DE CÓDIGO Y FORMATO: Herramienta de formato en línea de JSON : Herramienta de conversión mutua XML/JSON en línea: Código JSON Formateo en línea/embellecimiento/compresión/edición/herramientas de conversión: Herramientas de compresión/escape de JSON en línea: C estilo de lenguaje/HTML/CSS/JSON Código de formato y herramientas de embellecimiento:
http://tools.vevb.com/code/json
http://tools.vevb.com/code/jsonformat
http://tools.vevb.com/code/xmljson
http://tools.vevb.com/code/jsoncodeformat
http://tools.vevb.com/code/json_yasuo_trans
http://tools.vevb.com/code/ccode_html_css_json
Espero que este artículo sea útil para la programación Java de todos.