0

I have been looking for parsing JSON data in java/android. unfortunately, there is no JSON that same as mine. i have JSON data that include weird number, looks like :

{
"formules": [{"1":
    {
  "formule": "Linear Motion",
  "url": "qp1"
},"2":
{
  "formule": "Constant Acceleration Motion",
  "url": "qp2"
},"3":
{
  "formule": "Projectile Motion",
  "url": "qp3"
}
}
]
}

Please help me how to parse this in Java/android. Thanks

2
  • 2
    this is valid json...first create jsonobject, then get array from the jsonobject, and you will get it Commented May 15, 2015 at 13:14
  • yet another JSON problem ... there is no JSON that same as mine maybe, but there is bazillions similar, if you don't get it from similar JSON example, you should give up with programming at all Commented May 15, 2015 at 13:29

2 Answers 2

0

try this

JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("formules");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);

Now you can access object "1" as

JSONObject json = jsonObject1.getJSONObject("1");

or use iterator to iterate as below

Iterator keys = jsonObject1.keys();
while(keys.hasNext()) {
            // loop to get the dynamic key
            String currentDynamicKey = (String)keys.next();
            JSONObject json = jsonObject1.getJSONObject(currentDynamicKey);

        }

let me know if it works

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

1 Comment

hi apk, its works!! thank you so much. really appreciate it.
0

For parsing Json in Android, I have found the Gson Library to be helpful

http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3

What it would require is creating a pojo class that represents your object. Might look something like

public class ClassPojo
{
private Formules[] formules;

public Formules[] getFormules ()
{
    return formules;
}

public void setFormules (Formules[] formules)
{
    this.formules = formules;
}

@Override
public String toString()
{
    return "ClassPojo [formules = "+formules+"]";
}
}
public class Formules
{
private Formule 3;

private Forumle 2;

private Formule 1;



}

public class Formule
{
private String formule;

private String url;

public String getFormule ()
{
    return formule;
}

public void setFormule (String formule)
{
    this.formule = formule;
}

public String getUrl ()
{
    return url;
}

public void setUrl (String url)
{
    this.url = url;
}

@Override
public String toString()
{
    return "ClassPojo [formule = "+formule+", url = "+url+"]";
}
}       

then to convert it to and from JSon,you could use

//Convert to JSON
ClassPojo pojo = new ClassPojo();
Gson gson = new Gson();
String json = gson.toJson(pojo);

//COnvert back to Java object
ClassPojo pojo = gson.fromJson(json,ClassPojo.class);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.