1

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";
2
  • Did you already search for existing libraries for handling JSON data in Java...? Or did you try anything else so far? Commented Nov 15, 2015 at 11:15
  • I have been searching for a while now without finding any solution that I could implement. I have also tried out several solutions that I have found on the internet, but non of them helped me a lot. Commented Nov 15, 2015 at 11:20

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

0

You can convert the String in JSONObject:

JSONObject object = new JSONObject(jsonString);

And after get the fields:

object.getString("firstName");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.