How to read JSON file in Java with simple json? - java

If I have a JSON like this:
{
"name": "Johnny",
"Gender": {
"male": true,
"female": false
},
"What does Johnny likes?": ["Travels", "Woman"],
"Travels": [
{
"Country": "Spain",
"City": "Madrid"
},
{
"Country": "Greece",
"City": "Kalokairi"
}
]
}
I know that I can do this to access to name:
object.getString("name");
To access gender I can do this:
JSONObject gender = (JSONObject) object.get("Gender");
gender.get("male");
gender.get("female");
To access What does Johnny likes? I can:
JSONArray likes = (JSONArray) objet.get("What does Johnny likes?");
Iterator<String> iterator = likes.iterator();
while (iterator.hasNext()) {
//code here
}
But how do I access Travels? I'm really not sure to understand it?

did you, try this?
JSONArray travels = (JSONArray) objet.get("Travels");
for(int j=0;j<travels.length();j++){
JSONObject travel = travels.getJSONObject(j);
}

Related

Java: Array of Arrays from JSON

I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests

How to put multiple lists into one list?

Okay, so I need to put many different lists into one list using Java. Here is the important code.
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<List<String>> allInfo = new ArrayList();// list to put all the returned information
List<String> innerList = new ArrayList();
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
innerList.add(quesnum);
innerList.add(questype);
innerList.add(question);
innerList.add(ans1);
innerList.add(ans2);
innerList.add(ans4);
innerList.add(correctans);
innerList.add(category);
innerList.add(notes);
innerList.add(flag);
allInfo.add(innerList);
}
return allInfo;
As shown above, I take a List called innerList and put it into another List, which is of type List called allInfo. In the for loop, I take the length of the JSONArray I'm using, and add the elements to innerList. Then, I take innerList and add it into allInfo, then return that.
By the way, here is the JSON.
{
"error": false,
"message": "Request successfully completed",
"linemanques": [
{
"quesnum": 1,
"questype": 1,
"question": "This is question #1",
"ans1": "This is answer 1",
"ans2": "This is answer 2\r\n",
"ans3": "This is answer 3\r\n\r\n\r\n",
"ans4": "This is answer 4",
"correctans": "ans4",
"notes": "This is a note",
"category": "2",
"flag": "ans4"
},
{
"quesnum": 2,
"questype": 2,
"question": "This is question #2",
"ans1": "This is Q2 ans 1",
"ans2": "This is Q2 ans2",
"ans3": "This is Q2 ans3",
"ans4": "This is Q2 ans4",
"correctans": "ans2",
"notes": "This is Q2 note 1",
"category": "5",
"flag": "ans2"
},
{
"quesnum": 3,
"questype": 6,
"question": "gkjhgjkgkg",
"ans1": "ghdfhdghfd",
"ans2": "Tuituiyt",
"ans3": "Tiuytui9",
"ans4": "Tauitui.247",
"correctans": "ans2",
"notes": "Article iutuC",
"category": "5",
"flag": "ans2"
},
{
"quesnum": 7,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis\\r\\n",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
},
{
"quesnum": 8,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
},
{
"quesnum": 9,
"questype": 2,
"question": "How many apples can I eat in one day?",
"ans1": "42 apples",
"ans2": "6 apples",
"ans3": "89 apples",
"ans4": " 42 oranges",
"correctans": "ans2",
"notes": "try eating apples",
"category": "8",
"flag": "ans2"
},
{
"quesnum": 10,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis\\r\\n\\r\\n\\r\\n",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
}
]
}
And this is the structure of the array I'm hoping for:
allInfo {
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
}
But instead, this is what I'm ending up with (i think):
allInfo {
innerList {
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
}
}
It's supposed to make multiple lists in one list so that I can call access to it and set text in a TextView like this:
textView.setText(allInfo.get(2).get(4)); //example
I guess if you place the line List<String> innerList = new ArrayList(); within the for loop, it will properly initialize the innerList each time.
I think you do it in a hard way.
you could use a library to deserializes your JSON like Jackson
So you could build pojo class out your keys
import com.fasterxml.jackson.databind.ObjectMapper;
class Pojo {
String quesnum;
int questype;
String question;
String ans1;
String ans2;
String ans3;
String no;
String correctans;
String notes;
int category;
String flag;
}
then use Jackson to do the job for you by calling
List<Pojo> allInfo = mapper.readValue(json, new TypeReference<List<Pojo>>() {});
If i understood correctly, you forget to clean innerList within for loop. You need to do:
innerList.clear()

Return Java JsonPath as a json string

Using the java json path library: https://github.com/json-path/JsonPath
Given a json like this
{
"store": {
"book": [
{
"category": "reference"
},
{
"category": "fiction"
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
I would like to return "book" as a list of strings. For examples:
List<String> results = JsonPath.read(example, "$.store.book[*]");
And results should look like:
["{\"category\":\"reference\"}", "{\"category\":\"fiction\"}"]
Is there a way to achieve this?
Currently:
System.out.println(udf.jsonExtractScalar(testExample, "$.store.book[*]").getClass().getName());
--> net.minidev.json.JSONArray
As book is a JsonArray in you json tree, you can use JsonArray type and retrieve the data from it and add to the list.
Here is an example.
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
Replace jsonArrayString with you jsondata's books array name and you will be good to go.
The class used will be JSONArray class which is
`org.json.JSONArray`

How to dynamically simplify json using java?

I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.

Parsing JSON in java / Android [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I have this format of code. Can anyone help me how can I read the array? I need to read contacts array.
{
"success": true,
"contacts": [
{
"username": "ceema",
"profile": {
"name": "Ceema S",
"email": "ceemas#gmail.com",
"address": "No 143, gangaeyam, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
},
{
"username": "hari",
"profile": {
"name": "Harikrishnan V S",
"email": "harikriii#gmail.com",
"address": "No 143, harihome, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
},
{
"username": "pranav",
"profile": {
"name": "Pranav Mohan",
"email": "pranavmohan#gmail.com",
"address": "No 143, harihome, Maikkad P O, Kerala",
"phone": {
"mobile": "3333",
"home": "2222",
"office": "6666"
}
}
}
]
}
I tried this :
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//String id = c.getString(TAG_NAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
//String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
This jsonstr is json response from the site.
I need to read the nested contacts and populate it to
This jsonstr is json response from the site. I need to read the nested
contacts and populate it to
you got it almost right. The objects you are looking for are inside profile
JSONObject c = contacts.getJSONObject(i);
JSONObject profile = c.getJSONObject("profile");
and use profile instead of c, to look of name, phone and the others
check this link a very simple way to parse json
http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
The simplest way is to get POJO class from json using http://www.jsonschema2pojo.org/
You will get all the required classes to convert this json into POJO class,
and later you can use Gson library from google to convert json into Object and the other way around.
Think of this, if you get a Contact class as parent class then you can easily use fromjson method from Gson.
Gson gson=new Gson();
Contact contact = gson.fromJson(json_string, Contact.class);
Now you can easily use this class for further use.
Hope this helps.

Categories

Resources