简体   繁体   中英

Java Query SQL to JSON returns only one row

I am creating a webservice to query a database and return the data to JSON format for an Ajax call.

All is good until I try to return more than one row from my SQL database, my result then is

{"tag":"Ingredients","Items":"flour     ","Quantity":"6         "}

Note the spaces after the items and quantity tags, so I printed the query results to my console and realized that it is returning a multi-line result.

i tried to remove line breaks in case that was the issue but it did not seem to work.

Here is my JSON converter Utility.java

public static String constructSQLJSON(String tag, String string, String string2) {
        JSONObject obj = new JSONObject();
        String sqlout = null;
        try {
            obj.put("tag", tag);
            obj.put("Items", new String(string));
            obj.put("Quantity", new String(string2));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
        }
        return obj.toString();
    }

And my DB_probe.java

    while (rs.next()) {
        String items = rs.getString(1);
         items = items.replaceAll("\n ", " ").replaceAll("\n", " ");
        String Quantity = rs.getString(2);
         ingred = Utitlity.constructSQLJSON("Ingredients", items, Quantity);
        System.out.println( rs.getString(1) + rs.getString(2));

    }

I am using the codehaus.jettison.json package

Edit: I am using postman to test the results

If you suspect like that. you can trim String. try as follows

obj.put("Items", new String(string.trim()));
obj.put("Quantity", new String(string2.trim()));

Maybe you are looking for an example:

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonValue;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Class {
  public JsonValue constructSQLJSON(String tag,
                                           String string,
                                           String string2) {
    return Json.createObjectBuilder()
      .add("tag", tag)
      .add("Items", string.trim())
      .add("Quantity", string2.trim())
      .build();
  }

  public String someMethod() throws SQLException {
    final ResultSet rs = null;//..get result set...
    final JsonArrayBuilder results = Json.createArrayBuilder();
    while (rs.next()) {
      results.add(constructSQLJSON(
        "Ingredients",
        rs.getString(1),
        rs.getString(2)));
    }
    return results.build().toString();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM