I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
Related
I created a post request with json and it works pretty well. But now I want to insert the output of this json post request into my database.
So I need to create a json parser to seperate the string like this: "Bestellnummer:1", "Besteller:8195529", "Zeit: 2019-09-27 15:50:07", "Artikelnummer:76194", "Anzahl:1", "Preis:2.968"... (next Artikelnummer and so on...).
Bestellnummer = orderid, Besteller = customerid, Zeit = time, Artikelnummer=articleid, Anzahl = number of article, Preis= price
I tried to do something like a parser in my code, but I never did something like this befor and unfortuntly don't know how to involve this parser in my code.
I hope u can help me
One example for my json Output:
{"Bestellnummer":"1","Besteller":"8195529","Zeit":"2019-09-27 15:50:07","Artikel":[{"Artikelnummer":"76194","Anzahl":"1","Preis":"2.968"},{"Artikelnummer":"61681","Anzahl":"1","Preis":"7.147"},{"Artikelnummer":"111756","Anzahl":"1","Preis":"9.29"},{"Artikelnummer":"14227","Anzahl":"1","Preis":"0"}]}
Code:
private static String dirPath = "https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php";
public ArrayList<String> Bestellung(){
File file = new File (dirPath + "//array_complex.json");
ArrayList <String> test = new ArrayList<String>();
try {
String str = "{ \"Bestellnummer\": [1,2,3,4,5] }";
// holt alle 47550 bestellungen vom json
for (int i=1; i<2;i++) {
String POST_PARAMS = "json={\"bid\":\"bid\", \"getorder\":\""+i+"\"}";
//System.out.println(POST_PARAMS);
JSONObject obj1 = new JSONObject(POST_PARAMS);
JSONArray arr=obj1.getJSONArray("Bestellnummer");
for (int z=0; z<arr.length();z++) {
String post_id = arr.getJSONObject(z).getString("Bestellnummer");
System.out.println(post_id);
}
URL obj = new URL("https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("connection", "Keep-Alive");
postConnection.setDoOutput(true);
java.io.OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
//System.out.println("POST Response Code : " + responseCode);
// System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
test.add(response.toString());
// java.util.Iterator<String> it = test.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
}
}
}
catch (Exception e) {
System.out.println();
}
return test;
}
If what you want to do is to insert the HTTP response string into database, I strongly recommend you to deserialize the string to POJOs as follows:
Declare 2 classes - MyResponse and Artikel. Artikel is for storing the content of JOSN object in JSON array, and I use List<Artikel> for the JSON array. BTW, I also use #JsonProperty(provided in Jackson) to map JSON keys with uppercase to variables with lowercase.
class MyResponse {
#JsonProperty(value="Bestellnummer")
private String bestellnummer;
#JsonProperty(value="Besteller")
private String besteller;
#JsonProperty(value="Zeit")
private String zeit;
#JsonProperty(value="Artikel")
private List<Artikel> artikel;
//general getters and setters
}
class Artikel {
#JsonProperty(value="Artikelnummer")
private String artikelnummer;
#JsonProperty(value="Anzahl")
private String anzahl;
#JsonProperty(value="Preis")
private String preis;
//general getters and setters
}
Now, you can use Jackson (one of the most popular JSON libraries) to deserialize the HTTP response to our POJOs. And you can manipulate these POJOs for DB operation easily.
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(response.toString(), MyResponse.class);
myResponse.getArtikel().forEach(System.out::println);
Console output
Artikel [artikelnummer=76194, anzahl=1, preis=2.968]
Artikel [artikelnummer=61681, anzahl=1, preis=7.147]
Artikel [artikelnummer=111756, anzahl=1, preis=9.29]
Artikel [artikelnummer=14227, anzahl=1, preis=0]
Because you provided too less information to come up with a more detailed answer I came up with the following code.
JSONObject main = new JSONObject(data);
String orderNumber = main.getString("Bestellnummer"); // Retrieving the order number
String orderUserId = main.getString("Besteller"); // Retrieving the orderUserId
String time = main.getString("Zeit"); // Retrieving the current time
JSONArray articles = main.getJSONArray("Artikel"); // Getting articles as JSON Array
for (int i = 0; i < articles.length(); i++) { // Looping tough the articles
JSONObject article = articles.getJSONObject(i); // Getting the article JSON Object
String articleNumber = article.getString("Artikelnummer"); // Retrieving the Article number
String amount = article.getString("Anzahl"); // Retrieving the amount
String price = article.getString("Pris"); // Retrieving the price
// Your code...
}
I hope this helps you.
I'm parsing a jsonData and getting the video_url from it. What my requirements is to add the video_url inside the ArrayList. I've tried everything and getting the result as this in my logCat :
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FJIMyHoviVideo.mp4?alt=media&token=c103543e-31f0-4682-9b44-09d679c76699]
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Now here you can clearly see that the video_url is coming in this format what I want a single ArrayList containing both the url.
This is the code I've done to print the desired result but it is not coming fine :
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_url = null;
for(int i=0; i< jsonArray.length() ; i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_url = new ArrayList<>(Arrays.asList(jObject.getString("video_url")));
Log.e("VIDEO URL", video_url.toString());
}
}
I've tried in this way also but it failed, only one output is there if I'm doing in this way out of the loop.
for( String string : video_url){
ArrayList<String> string1 = new ArrayList<>();
string.add(string);
Log.e("LOGS", string1.toString());
}
for the above code the output is coming only one and in this format :
E/LOGS: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Please help me with this, I've tried a lot. Thanks.
You are creating a new ArrayList every loop iteration. You should use add instead!
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_urls = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_urls.add(jObject.getString("video_url"));
}
}
So far with the code I have, I am able to get results as a JsonObject. However, I am trying to get the coordinates of the location based on the postal code that I have entered. How can I retrieve the "lat" and "lng" as Strings/JsonElements? Would really appreciate if you can give me some insight. Thanks!
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
//the JSON builder
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String restaurant = request.getParameter("r");
String customer = request.getParameter("c");
//Get coordinates of the restaurant
String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
URL url = new URL(longLatApi);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", longLatApi);
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
out.println(gson.toJson(obj));
JsonElement and its subclasses have nice methods to iterate through JSON elements of different kinds: null, a primitive (numbers, string literals, and booleans), a JSON object, or a JSON array. Knowing an exact structure of the response JSON document, you can extract child elements pretty straight-forward:
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
final JsonParser jsonParser = new JsonParser();
// Extract the `results` array
final JsonArray resultsJsonArray = jsonParser.parse(reader)
.getAsJsonObject()
.get("results")
.getAsJsonArray();
// Iterate over each result array element
for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
// Picking up the `geometry` property as a JSON object
final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
// And dumping the location
final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
dumpLocationJsonObject("Location", locationJsonObject);
final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
// There can be a `bounds` object with two additional properties
if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
}
}
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}
The output:
Greenwich, London SE10, UK
Location: (51.48257659999999; -0.0076589)
As an alternative approach, you can define custom JSON to Java classes mappings in order to deserialize the JSON document as a custom class instance, and not just JsonElement (something like gson.fromJson(reader, customType)). Both approaches have pros and cons.
I am getting this from server
"[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]"
The above text is not an array, but a string returned from server.
I want to convert this in an ArrayList
Is there a way to convert it?
There is no good idea to manually parse that string. You should use a library that parses JSON strings for you. Anyhow the given string is not a valid JSON string and like others have mentioned you should request JSON formatted data from the server.
If your server only returns like this and you need to manually parse then this would be a solution. Not a very good one, but it does the job.
public static void main(String[] args) {
List<String> words = new ArrayList<>();
String string = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
String withoutBrackets = string.replaceAll("[\\[\\](){}]", ""); // Remove all the brackets
for (String word : withoutBrackets.split(",")) {
String singleWord = word.replaceAll("\"", "");
words.add(singleWord);
}
System.out.println(words);
}
Can be done using separator, where s is String:
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Try using Gson. Add this to your gradle
compile 'com.google.code.gson:gson:2.2.4'
Hope this helps -
String str = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
Gson gson=new Gson();
ArrayList<String> strings = gson.fromJson(str,new TypeToken<ArrayList<String>>(){}.getType());
This will work
String text = [\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
text = text.replaceAll("[\\[\\](){}\"]", "");
List<String> list = Arrays.asList(text.split(","));
Modify your String using
str = str.replace ("[", "").replace ("]", "");
so it is the same as
String str = "\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"";
then use
List<String> al = new ArrayList<String>(Arrays.asList(str.split(",")));
System.out.println(al);
This is the correct way to parse JSON String to ArrayList :)
ArrayList<String> list = new ArrayList<String>();
String newArrayy ="[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
imagePath = newArrayy;
try {
JSONArray jsonArray = new JSONArray(imagePath);
if (null != jsonArray) {
Logger.LogError("imagePathhh", jsonArray.toString() + "" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
String value =(String) jsonArray.getString(i);
list.add(value); dataBaseCurdOperation.insertPaymentPath(jsonArray.getString(i));
}
} else {
}
} catch (Exception e) {
}
}
Sanjay in his answer pointed it out correct , that it is not correct format.
Still if you are using Gson library to parse JSON data, then the following method take care of this format also. So you have no need to do anything :)
new Gson().fromJson(your_server_response, Model.class);
One more way to do this is using java's inbuilt method
public String replaceAll (String regularExpression, String replacement)
I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}