1

I have this Json statement :

{name=Adam Schmidt, id=43}

and I want to extract the value of the name, trying this code but it didn't work

// parse json data
        try {
            JSONObject userObject = new JSONObject(result);
            userName = userObject.getString("name");
                    tvName.setText(userName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
1
  • 3
    is it a valid json? jsonlint.com check here Commented Sep 20, 2013 at 18:32

2 Answers 2

2

You statement is not valid json. Here's the sample of valid json.

{\"name\":\"Adam Schmidt\", \"id\":43} 

Update: For number value, no quotation mark

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

Comments

0

Use GSON. Super easy.

Declare a class that represents your JSON structure:

public class Person {
  private String name;
  private int id;

  public String getName() {
    return name;
  }

  public int getId() {
    return id;
  }
}

Then you can do:

String json = "{\"name\":\"Adam Schmidt\", \"id\":43}";
String userName = new Gson().fromJson(json, Person.class).getName();
tvName.setText(userName);

This is much better than haphazardly parsing chunks with various get methods all over your code. Plus you get a nice object to pass around and use in your object oriented code.

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.