Reputation: 564
Using gson how can I return the first and last element from my json so I get the data in this format?
System.out.println("Student: BobGoblin - result: 59");
I have tried this, but it still returns the full JSON object
JsonObject jsonObject = new Gson().fromJson(content.toString(), JsonObject.class);
return jsonObject.get(domain) + " - " + jsonObject.get(result.toString());
Upvotes: 0
Views: 371
Reputation: 8105
First of all: toJson converts something to json. You want to convert json to some kind of object. So use fromJson
instead.
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
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. Then access that java object to get to your data.
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.
Upvotes: 2