Grabbing all the Values of a JSON Object

Asked

Viewed 10,681 times

4

I wonder how to get all the values of a part of the JSON:

{
    "Message": "The request is invalid.",
    "ModelState": {
        "produto.pro_descricao": ["Informe a descrição do Produto."],
        "produto.pro_grupo": ["Grupo informado inexistente."]
    }
}

Where I’d like to get all the values from the ModelState and put them in a string.

Thus remaining:

Please provide the description of the Product. Group reported missing.

With the code below:

jSubPar := LJSONObject.Get('ModelState');

I got the following result:

"ModelState": {
    "produto.pro_descricao": ["Informe a descrição do Produto."],
    "produto.pro_grupo": ["Grupo informado inexistente."]
}

But I only need the descriptions.

2 answers

3


First declare a uses System.JSON;

Json would be:

jsonString := {"jsonteste":[{"campo1":"valor1"}]}

Then to read the json:

jsonRaiz := TJSONObject.ParseJSONValue(jsonString) as TJSONObject;
if(jsonRaiz <> nil)then
begin
    jsArray := jsonRaiz.GetValue<TJSONArray>('jsonteste') as TJSONArray;
    for i := 0 to jsArray .Count-1 do
    begin
      jsonObject := jsArray.Items[i] as TJSONObject;
      showmessagem(jsonObject.GetValue<string>('campo1'));
    end;
end;

answer would be the "valor1"

-1

function getCamposJsonString(json,value:String): String;
var
   LJSONObject: TJSONObject;
   function TrataObjeto(jObj:TJSONObject):string;
   var i:integer;
       jPar: TJSONPair;
   begin
        result := '';
        for i := 0 to jObj.Size - 1 do
        begin
             jPar := jObj.Get(i);
             if jPar.JsonValue Is TJSONObject then
                result := TrataObjeto((jPar.JsonValue As TJSONObject)) else
             if sametext(trim(jPar.JsonString.Value),value) then
             begin
                  Result := jPar.JsonValue.Value;
                  break;
             end;
             if result <> '' then
                break;
        end;
   end;
begin
   try
      LJSONObject := nil;
      LJSONObject := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(json),0) as TJSONObject;
      result := TrataObjeto(LJSONObject);
   finally
      LJSONObject.Free;
   end;
end;

Browser other questions tagged

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