简体   繁体   English

如何返回 Json 的第一个和最后一个元素

[英]How To Return First And Last Element Of Json

Using gson how can I return the first and last element from my json so I get the data in this format?使用 gson 如何从我的 json 返回第一个和最后一个元素,以便以这种格式获取数据?

System.out.println("Student: BobGoblin - result: 59");

I have tried this, but it still returns the full JSON object我试过了,但它仍然返回完整的 JSON 对象

JsonObject jsonObject = new Gson().fromJson(content.toString(), JsonObject.class);
return jsonObject.get(domain) + " - " + jsonObject.get(result.toString());

First of all: toJson converts something to json.首先:toJson 将某些内容转换json。 You want to convert json to some kind of object.您想将 json 转换为某种对象。 So use fromJson instead.所以改用fromJson

Second build an object where you can put that data into.其次构建一个对象,您可以将数据放入其中。 There are plenty examples on the manual site for gson: https://github.com/google/gson/blob/master/UserGuide.md gson 的手册站点上有很多示例: https : //github.com/google/gson/blob/master/UserGuide.md

Let me code that for you.让我为你编码。 It's not that hard:这并不难:

import java.util.Map;

import com.google.gson.Gson;

public class GsonTest {

    public static void main(String args[]) {

      Gson gson = new Gson();

      String json = "{\"name\":\"Bog\", \"foo\":\"bar\", \"result\": 59}";

      // Using a map
      @SuppressWarnings( "unchecked" )
      Map<String,Object> map = gson.fromJson( json, Map.class );
      System.out.println( "Name: " + map.get( "name" ) + " result: " + map.get( "result" ) );

      // Better: using an object
      Student student = gson.fromJson( json, Student.class );
      System.out.println( "Name: " + student.name + " result: " + student.result );

    }

    public static class Student {
        public String name;
        public String foo;
        public int result;
    }
}

which will result in:这将导致:

Name: Bog result: 59.0
Name: Bog result: 59

The general Method is: Take the json String and put it in some kind of java object.一般的方法是:将json字符串放入某种java对象中。 Then access that java object to get to your data.然后访问该 java 对象以获取您的数据。

Note that you get more control over the kind of data you will receive using the second method.请注意,您可以更好地控制使用第二种方法接收的数据类型。 Since json doesn't specify the datatype the parser guesses float/double for age while it uses int in the second example because the class said so.由于 json 没有指定数据类型,解析器在第二个示例中使用int时猜测年龄是float/double因为类是这样说的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM