Get Json properties name

Asked

Viewed 828 times

-1

How do I get the properties names of a Json using the library Gson?

Input example:

{
   "Ficha":[
      {
         "nome":"nome",
         "sobrenome":"sobrenome",
         "idade":"idade",
         "endereco":"endereco",
         "empresa":"empresa",
         "telefones":[
            {
               "residencial":"residencial"
            },
            {
               "celular":"celular"
            }
         ]
      }
   ]
}

Expected exit:

["nome", "sobrenome", "idade", "endereco", "empresa", "telefones", ...
  • look misspelled have to print so ["name","last name","age"].... the names of the properties

  • You talk in the library gson, then the language is Java, not Javascript, correct? If so, please remove the tag javascript of the question.

2 answers

1

Follow one of the ways to do what you seek:

var json = {
  "Ficha": [{
    "nome": "nome",
    "sobrenome": "sobrenome",
    "idade": "idade",
    "endereco": "endereco",
    "empresa": "empresa",
    "telefones": [{
      "residencial": "residencial"
    }, {
      "celular": "celular"
    }]
  }]
};

var output = [];

for (property in json.Ficha[0]) {
  output.push(property);
  // Uma propriedade de cada vez
  alert(property);
}

// Caso deseje utilizar todas as propriedades de uma única vez
alert(output.join(' | '));

0


Using the Gson, you can use the method entrySet to obtain all the properties of a JsonObject, as shown in the example below.

String json =
    "{" +
        "\"Ficha\":[" +
            "{" +
                "\"nome\":\"nome\"," +
                "\"sobrenome\":\"sobrenome\"," +
                "\"idade\":\"idade\"," +
                "\"endereco\":\"endereco\"," +
                "\"empresa\":\"empresa\"," +
                "\"telefones\":[" +
                    "{" +
                        "\"residencial\":\"residencial\"" +
                    "}," +
                    "{" +
                        "\"celular\":\"celular\"" +
                    "}" +
                "]" +
            "}" +
        "]" +
    "}";
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
JsonObject primeiraFicha = json.get("Ficha").getAsJsonArray().get(0).getAsJsonObject();
Set<Entry<String, JsonElement>> properties = primeiraFicha.entrySet();
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (Entry<String, JsonElement> property : properties) {
    if (!first) sb.append(",");
    first = false;
    sb.append(property.getKey());
}
sb.append("]");
System.out.println(sb.toString());
  • Carlosfigueira could send me the imports this giving error

  • You need import Jsonelement, Jsonobject and Jsonparser from com.google.gson in addition to java.util.Map.Entry and java.util.Set

  • you also work with fasterXML

Browser other questions tagged

You are not signed in. Login or sign up in order to post.