JSON
Parsing JSON string
Ricerca…
Analizza la stringa JSON utilizzando la libreria com.google.gson in Java
com.google.gson
necessario aggiungere la libreria com.google.gson
per utilizzare questo codice.
Ecco la stringa di esempio:
String companyDetails = {"companyName":"abcd","address":"abcdefg"}
Le stringhe JSON possono essere analizzate usando la sintassi sottostante in Java:
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(companyDetails);
JsonObject jsonObj = jsonElement.getAsJsonObject();
String comapnyName = jsonObj.get("companyName").getAsString();
Analizza la stringa JSON in JavaScript
In JavaScript, l'oggetto JSON
viene utilizzato per analizzare una stringa JSON. Questo metodo è disponibile solo nei browser moderni (IE8 +, Firefox 3.5+, ecc.).
Quando viene analizzata una stringa JSON valida, il risultato è un oggetto JavaScript, un array o altro valore.
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)
Le stringhe non valide generano un errore 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
Il metodo JSON.parse
include una funzione reviver opzionale che può limitare o modificare il risultato dell'analisi
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}
Nell'ultimo esempio, JSON.parse
restituisce un valore undefined
. Per evitare ciò, restituire il value
all'interno della funzione Reviver.
Analizza file JSON con Groovy
Supponiamo di avere i seguenti dati JSON:
{
"TESTS":
[
{
"YEAR": "2017",
"MONTH": "June",
"DATE": "28"
}
]
}
import groovy.json.JsonSlurper
class 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");
}
Di seguito è riportato il parser:
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
}
}