Reputation: 31
I get the following JSON from a server and I would like to save all the values in different variables. Now everything is saved as one string variable.
{"firstName":"Jim","lastName":"Smith"}
What I would like to is to separate them and put them into two variables like in the example below. The firstName
and lastName
will be various, depending on what the server is sending to me.
String personFirstName= "Jim";
String personLastName = "Smith";
Upvotes: 1
Views: 10926
Reputation: 539
You can convert the String
in JSONObject
:
JSONObject object = new JSONObject(jsonString);
And after get the fields:
object.getString("firstName");
Upvotes: 0
Reputation: 3353
An example for you:
Read Json into str (a string value), then:
JSONObject obj= new JSONObject(str);
String personFirstName = obj.getString("firstName");
String personLastName = obj.getString("lastName");
hope this help!
Upvotes: 1
Reputation: 42481
I suggest to use one of many JSON processing libraries available.
Examples are Gson and Jackson.
Both of them allow to convert: json string <--> object
You should start with defining domain model:
public class Person {
private String firstName;
private String lastName;
// getters/setters
}
Then you should do like this (for example, for GSON):
String json = "{\"firstName\":\"Jim\",\"lastName":\"Smith\"}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
Hope this helps
Upvotes: 5