Buscar..


Analice la cadena JSON utilizando la biblioteca com.google.gson en Java

com.google.gson debe agregar la biblioteca com.google.gson para usar este código.

Aquí está la cadena de ejemplo:

String companyDetails = {"companyName":"abcd","address":"abcdefg"}

Las cadenas JSON se pueden analizar utilizando la siguiente sintaxis en Java:

JsonParser parser =  new JsonParser();
JsonElement jsonElement = parser.parse(companyDetails);
JsonObject jsonObj = jsonElement.getAsJsonObject();
String comapnyName = jsonObj.get("companyName").getAsString();

Parse JSON cadena en JavaScript

En JavaScript, el objeto JSON se utiliza para analizar una cadena JSON. Este método solo está disponible en los navegadores modernos (IE8 +, Firefox 3.5+, etc.).

Cuando se analiza una cadena JSON válida, el resultado es un objeto JavaScript, una matriz u otro valor.

JSON.parse('"bar of foo"')
// "bar of foo" (type string)
JSON.parse("true")
// true (type boolean)
JSON.parse("1")
// 1 (type number)
JSON.parse("[1,2,3]")
// [1, 2, 3] (type array)
JSON.parse('{"foo":"bar"}')
// {foo: "bar"} (type object)
JSON.parse("null")
// null (type object)

Las cadenas no válidas lanzarán un error de JavaScript

JSON.parse('{foo:"bar"}')
// Uncaught SyntaxError: Unexpected token f in JSON at position 1
JSON.parse("[1,2,3,]")
// Uncaught SyntaxError: Unexpected token ] in JSON at position 7
JSON.parse("undefined")
// Uncaught SyntaxError: Unexpected token u in JSON at position 0

El método JSON.parse incluye una función reviver opcional que puede limitar o modificar el resultado del análisis.

JSON.parse("[1,2,3,4,5,6]", function(key, value) {
  return value > 3 ? '' : value;
})
// [1, 2, 3, "", "", ""]

var x = {};
JSON.parse('{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}', function(key, value) {
  if (value > 3) { x[key] = value; }
})
// x = {d: 4, e: 5, f: 6}

En el último ejemplo, JSON.parse devuelve un valor undefined . Para evitar eso, devuelva el value dentro de la función de revivimiento.

Parse JSON archivo con Groovy

Supongamos que tenemos los siguientes datos JSON:

{
    "TESTS": 
    [
         {
              "YEAR": "2017",
              "MONTH": "June",
              "DATE": "28"                  
         }
    ]
}

importar groovy.json.JsonSlurper

clase JSONUtils {

private def data;
private def fileName = System.getProperty("jsonFileName")

public static void main(String[] args)
{
    JSONUtils jutils = new JSONUtils()
    def month = jutils.get("MONTH");
}    

A continuación se muestra el analizador:

private parseJSON(String fileName = "data.json")
{ 
    def jsonSlurper = new JsonSlurper()
    def reader

    if(this.fileName?.trim())
    {
        fileName = this.fileName
    }

    reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
    data = jsonSlurper.parse(reader);
    return data
}

def get(String item)
{
    def result = new ArrayList<String>();
    data = parseJSON()        
    data.TESTS.each{result.add(it."${item}")}
    return  result
}        

}



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow