I have a string that looks like this
"{"resturant_name": "Chipotle", "street": "431 Liberty St"},
{"resturant_name": "MCDoNalds", "street": "1 Main St"},
{"resturant_name": "Wednys", "street": "5 Main St"}"
And I want to turn into a JSONArray so I can loop though and get the name?
But when I do
JSONArray jsonArray = new JSONArray(string);
I get an error
type of org.json.JSONObject cannot be converted to JSONArray,
How can I make this a JSONArray so I can loop though it?
Thanks
That's because your string is not JSON. It's close, but not quite. JSON standards dictate that the structure should either be an Object or an Array. To create an Array, it must begin with "[" and end with "]". So, your string should look like:
[{"resturant_name": "Chipotle", "street": "431 Liberty St"},
{"resturant_name": "MCDoNalds", "street": "1 Main St"},
{"resturant_name": "Wednys", "street": "5 Main St"}]
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am completely stuck on this and need help.
I need to get the value if another value is equal to something.
Lets say my array is:
"people":[
{"name": "David", "age": "30"},
{"name": "Bob", "age": "20"},
{"name": "Bill", "age": "30"}
]
I need to return the age if the name is lets say Bob. I have attempted to do it this way but to no avail.
String People = jsonPart.getString("people");
JSONArray arr = new JSONArray(People);
for (int h = 0; h < arr.length(); h++) {
JSONObject jsonPart = arr.getJSONObject(h);
String name = jsonPart.getString("name");
if (name == "Bob") {
String age = jsonPart.getString("age");
break;
}
}
Your problem is that you cannot do String comparisons in Java using the == operator. You must use String#equals so replace this line:
if (name == "Bob") {
with
if(name.equals("Bob")) {
See this link for more info:
https://www.baeldung.com/java-compare-strings
and
https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html
You can also do it like this:
If("Bob".equals(name))
to avoid NullPointerException if the name is null.
I am reading some data from the internet into my array like this:
final String[] relations = entity.getAsJsonPrimitive("rel").getAsString().substring(1).split("\\/");
final String relation = entity.getAsJsonPrimitive("rel").getAsString();
System.out.println(relations[1]);
break;
Anyway, the output is really weird (without the break statement the output is hundred of lines) since after I added the break statement I am getting two lines of output like this:
proerty
is_a
How can I split this output to print only the first or the second line?
I checked how the function spilt works but it did not work for me it says "ArrayIndexOutOfBound"
Also, would any one tell me why the first index contains hundred of lines but the second index throws an error when I print it and says out of bound.
This is the input, which is only one element. The real input has hundreds elements like this one:
Note: I want to print the relation part only.
{
"context": "/ctx/all",
"dataset": "/d/verbosity",
"end": "/c/en/sleep",
"features": [
"/c/en/bed /r/RelatedTo -",
"/c/en/bed - /c/en/sleep",
"- /r/RelatedTo /c/en/sleep"
],
"id": "/e/bffe7778135422c9fc697e5c3ada0be01ef026f0",
"license": "/l/CC/By-SA",
"rel": "/r/RelatedTo",
"source_uri": "/s/site/verbosity",
"sources": [
"/s/site/verbosity"
],
"start": "/c/en/bed",
"surfaceText": "[[bed]] is related to [[sleep]]",
"uri": "/a/[/r/RelatedTo/,/c/en/bed/,/c/en/sleep/]",
"weight": 6.954197039975413
},
Thanks in advance!
I have string from which I am getting data in array but I am not getting way to get so that I get related data in array like my string is,
[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}], "
here i have two dropdowns ,
"Class Room" having two values in dropdown Windows and Windows1
another drodown,
"Staffroom" having two values in dropdown Windows and Windows1
How would i get dropdown related value in array i can use split operation but cant getting logic
Above given string is in list, my code is ,
String[] data = list.toString().split(",");
But it split in array then I would not have related data
I want it to split in way so that I would get relative dropdown data in array,
"Class Room": ["Windows", "Windows1"], value in aray index 0
"Staffroom": ["Windows", "Windows1"]}] value in array index 1
String is not fix it is generating on run time number of dropdown and values of dropdown vary time to time but pattern of string same as mentioned above
This depends on the UI framework that you are working. If you are using Swings then you have to use ActionListener to display related data. For example
private String s1[] = { "None", "J2EE", "DataBase", "Scripting Language",
"Computer Networks" };
private String s2[][] = { { "None" }, { "Core Java", "Advanced Java" },
{ "Oracle", "SQL", "SyBase" }, { "Java scripts", "c#", "CGI" },
{ "MCSE", "CCNA", "CCNP", "CCIE" } };
...
skill = new JComboBox(s1);
specificSkill = new JComboBox(s2[0]);
...
skill.addActionListener(new ComboAction());
...
specificSkill.setSelectedIndex(0);
You can use this code which can solve your problem as it is tested and verified.
String temp = "[{"Class Room": ["Windows", "Windows1"], "Staffroom": ["Windows", "Windows1"]}],";
String parts[] = temp.split(",");
ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < parts.length; i =i+2) {
listItems.add(parts[i]+","+parts[i+1]);
}
Or you can use regex to break the string at a particular occurence of a character.
I hope it helps.
I'm new to JSON and I'm really struggling to parse this layout with GSON in Java
{"time_entries":
[
{"hours":1.0,
"id":311,
"created_on":"2012-11-02T14:53:38Z",
"user":{"id":7,"name":"blah"},
"issue":{"id":266},
"activity":{"id":10,"name":"blah"},
"updated_on":"2012-11-02T14:53:38Z",
"comments":"blah",
"spent_on":"2012-11-02",
"project":{"id":10,"name":"blah"}},
{"hours":6.0,
"id":310,
"created_on":"2012-11-02T13:49:24Z",
"user":{"id":4,"name":"blah"},
"issue":{"id":258},
"activity":{"id":9,"name":"blah"},
"updated_on":"2012-11-02T13:49:24Z",
"comments":"blah",
"spent_on":"2012-11-02",
"project":{"id":11,"name":"blah"
}}
],
"offset":0,
"limit":2,
"total_count":306
}
If it helps it's the output the Redmine API gives you for time entries.
I'm struggling to understand some of the basic JSON concepts like objects and arrays and I haven't been able to find an example with a layout similar to this.
My main concern in using the tutorials I have read is that the multiple ID fields will get confused.
What's the best way to parse this without tying myself in knots?
I'm not set on using Gson and would be happy for a solution using Jackson or the built in library. The end goal is for Android implementation so I would prefer to use use serialization.
Thanks
EDIT:
My attempt at an "object model"
public class TimeResponse {
public List<Time_Entry> time_entries;
#SerializedName("hours")
public String hours;
#SerializedName("id")
public int id;
#SerializedName("created_on")
public String created_on;
#SerializedName("name")
public String name;
#SerializedName("updated_on")
public int updated_on;
public int page;
#SerializedName("comments")
public double comments;
#SerializedName("spent_on")
public String spent_on;
#SerializedName("offset")
public String offset;
#SerializedName("limit")
public String limit;
#SerializedName("total_count")
public String total_count;
}
I'm am unsure as to what I should write for my results list (if I need one) and I've have only declared an id and name string once despite it being used multiple times?
I am aware I shouldn't be using strings for my hours I'm in the process of looking into what the hours field actually contains. I believe the tutorial is slightly out of date in that the last three fields are not represented in the same way now in the Twitter API.
I am not sure what you mean by 'multiple ID fields'. There is no such thing as an ID in JSON.
Regarding the basic JSON concepts, see http://json.org/:
Object:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Array:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
Value:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
String:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Number:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
Edit:
There is not much you can do to simlify the JSON from your question except pretty-print it:
{
"time_entries": [
{
"hours": 1,
"id": 311,
"created_on": "2012-11-02T14:53:38Z",
"user": {
"id": 7,
"name": "blah"
},
"issue": {
"id": 266
},
"activity": {
"id": 10,
"name": "blah"
},
"updated_on": "2012-11-02T14:53:38Z",
"comments": "blah",
"spent_on": "2012-11-02",
"project": {
"id": 10,
"name": "blah"
}
},
{
"hours": 6,
"id": 310,
"created_on": "2012-11-02T13:49:24Z",
"user": {
"id": 4,
"name": "blah"
},
"issue": {
"id": 258
},
"activity": {
"id": 9,
"name": "blah"
},
"updated_on": "2012-11-02T13:49:24Z",
"comments": "blah",
"spent_on": "2012-11-02",
"project": {
"id": 11,
"name": "blah"
}
}
],
"offset": 0,
"limit": 2,
"total_count": 306
}
Perhaps you can see that you have one JSON Object with four name/value pairs:
time_entries
offset
limit
total_count
The last three of these have simple numeric values while the first (time_entries) is an Array of two more Objects. Each one of these two Objects conssits of various name/value pairs. The name/value pair id is just one of these.
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
I ve used javascript here.. it may useful for you.. if you 've any other help let me knw
var jsonText = xmlhttp.responseText;
var obj = eval ("(" + jsonText + ")");
row_num=Object.keys(obj.time_entries).length;
this line give the length of time_entries array length
keydata[c]=Object.keys(obj.time_entries[0]);
columndata=keydata[0].toString();
my = columndata.split(",");
columndata contain the key values of time entries as a string of zero th index in that array
columnndata={hours,id,create_on..... and so on}
my={"hours","id".... etc}
If you pass multiple JSON arrays into Java (in a single stream) that looks like this:
[ <-----json objects---->] [ <-----json objects---->] [ <-----json objects---->]
How do you parse in Java? And is there a way to do it without rewriting the JSON data into a single array?
Essentialy, I want to get to a point where I can do this after the parsing.
item = json.getString("item");
total = json.getString("total");
items.add(item);
totals.add(total);
A key note is that the first array is items, the second array is totals. The first json object in items corresponds to the first in totals.
I would say that you need first of all transform this content in a valid JSON, maybe you could first replace ]\s*[ by ],[ and add [ at the beggining and ] at the end. This would be a valid JSON and could be parsed as an JSONArray that contains many JSONArrays.
Something like:
String receivedJSON = "[{},{}] [{},{}] [{}]";
String normalized = "[" + receivedJSON.replaceAll("\\]\\s*\\[", "],[") + "]";
new JSONArray(normalized);