如何使用Servlet创建Json

时间:2013-01-27 14:06:28

标签: java json servlets

如何使用servlet创建类似此代码的JSON数组(见下文)?现在我在String中手动编写代码并将其转换为JSON数组,但我总是得到一个错误:

错误:

Error parsing data org.json.JSONException: Expected literal value at character 982 of


{
    "question": [
        {
            "text": "",
            "answers": [  { "a1": "" }, { "a2": "" }, { "a3": "" } ],
            "correctAnswers": [ { "ra1": "" }, { "ra2": ""  }, { "ra3": "" } ],
            "explanation": ""
        },
    .
    .
    .
    ]
}

这是servlet代码:有些部分是德语,对不起,如果你有理解

StringBuffer sb = new StringBuffer();
        ArrayList<Integer> kapitel = new ArrayList<Integer>();

        String text = "false";
        // boolean check = false;

        for (int i = 0; i < 14; i++) {
            if ("1".equals(request.getParameter("k" + (i + 1))))
                kapitel.add(i + 1);
        }


        String arrayFragen[][] = null;
        String arrayAntworten[][] = null;
        String[] antwortSeatze = null;
        String[] richtigeAntwortSeatze = null;

        Main main = new Main();
        Datenbank db = new Datenbank();

        main.frageAntworten(kapitel);


        arrayAntworten = main.antworten;
        arrayFragen = main.fragen;

        int zeahler = 1;
        String frageId;
        sb.append("{");
        sb.append("\n\"frage\": [");

        for (int i = 0; i < arrayFragen.length - 1; i++) {
            frageId = arrayFragen[i][0];

            sb.append("\n{");
            sb.append("\n\"text\": \"" + arrayFragen[i][1] + "\", ");
            sb.append("\n\"antworten\": [");

            antwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                    arrayAntworten)];
            int x = 0;
            for (int j = 0; j < arrayAntworten.length; j++) {
                if (arrayAntworten[j][0].equals(frageId))
                    antwortSeatze[x++] = arrayAntworten[j][1];
            }
            zeahler = 1;
            for (int j = 0; j < antwortSeatze.length - 1; j++) {
                sb.append("\n{\"a" + zeahler++ + "\": \"" + antwortSeatze[j]
                        + "\"}, ");
            }

            // letze Antwortmöglichkeit
            sb.append("\n{\"a" + zeahler++ + "\": \""
                    + antwortSeatze[antwortSeatze.length - 1] + "\"} ");
            sb.append("\n],");

            richtigeAntwortSeatze = new String[db.arraySizeAntwortenSeatze(
                    frageId, arrayAntworten)];

            // Richige Antworten
            sb.append("\n\"richtigeantworten\": [");
            antwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                    arrayAntworten)];
            int y = 0;
            for (int j = 0; j < richtigeAntwortSeatze.length; j++) {
                if (arrayAntworten[j][0].equals(frageId))
                    if (arrayAntworten[j][2].equals("false"))
                        antwortSeatze[y++] = "null";
                if (!(arrayAntworten[j][2].equals("false")))
                    antwortSeatze[y++] = arrayAntworten[j][1];
            }
            zeahler = 1;
            for (int j = 0; j < antwortSeatze.length - 1; j++) {
                sb.append("\n{\"ra" + zeahler++ + "\": \"" + antwortSeatze[j]
                        + "\"}, ");

                // letze Richtige Antwortmöglichkeit
            }
            sb.append("\n{\"ra" + zeahler++ + "\": \""
                    + antwortSeatze[antwortSeatze.length - 1] + "\"} ");
            sb.append("\n],");

            richtigeAntwortSeatze = new String[db.arraySizeAntwortenSeatze(
                    frageId, arrayAntworten)];

            sb.append("\n\"erklaerung\": \"" + arrayFragen[i][2] + "\", ");
            sb.append("\n},");
        }

        // Letzte Frage
        frageId = arrayFragen[arrayFragen.length - 1][0];

        sb.append("\n{");
        sb.append("\n\"text\": \"" + arrayFragen[arrayFragen.length - 1][1]
                + "\", ");
        sb.append("\n\"antworten\": [");

        antwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                arrayAntworten)];
        int x = 0;
        for (int j = 0; j < arrayAntworten.length; j++) {
            if (arrayAntworten[j][0].equals(frageId))
                antwortSeatze[x++] = arrayAntworten[j][1];
        }
        zeahler = 1;
        for (int j = 0; j < antwortSeatze.length - 1; j++) {
            sb.append("\n{\"a" + zeahler++ + "\": \"" + antwortSeatze[j] + "\"},");
        }
        // letze Antwort möglichkeit
        sb.append("\n{\"a" + zeahler++ + "\": \""
                + antwortSeatze[antwortSeatze.length - 1] + "\"} ");
        sb.append("\n],");

        richtigeAntwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                arrayAntworten)];

        sb.append("\n\"richtigeantworten\": [");
        antwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                arrayAntworten)];
        int y = 0;
        for (int j = 0; j < richtigeAntwortSeatze.length; j++) {
            if (arrayAntworten[j][0].equals(frageId))
                if (arrayAntworten[j][2].equals("false"))
                    antwortSeatze[y++] = "null";
            if (!(arrayAntworten[j][2].equals("false")))
                antwortSeatze[y++] = arrayAntworten[j][1];
        }
        zeahler = 1;
        for (int j = 0; j < antwortSeatze.length - 1; j++) {
            sb.append("\n{\"ra" + zeahler++ + "\": \"" + antwortSeatze[j]
                    + "\" },");
        }

        // letze Richtige Antwortmöglichkeit
        sb.append("\n{\"ra" + zeahler++ + "\": \""
                + antwortSeatze[antwortSeatze.length - 1] + "\"} ");
        sb.append("\n],");

        richtigeAntwortSeatze = new String[db.arraySizeAntwortenSeatze(frageId,
                arrayAntworten)];

        sb.append("\n\"erklaerung\": \"" + arrayFragen[arrayFragen.length - 1][2]
                + "\", ");
        sb.append("\n}");

        sb.append("\n]");
        sb.append("\n}");

        text = sb.toString();


        response.getWriter().print(text);
        System.out.println(text);

android部分:

private  class JSONParser extends AsyncTask<URL, String, String> {

        @Override
        protected String doInBackground(URL... url) {
            InputStream is = null;
            String json = "";

            // VERBINDUNGSAUFBAU
            try {
                URLConnection connection = url[0].openConnection();
                HttpURLConnection http = (HttpURLConnection)connection;
                int response = http.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                is = http.getInputStream();}


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // CONVERTIERUNG VON INPUTSTREAM ZU STRING

            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            return json;


//          InputStream is =  m.getData(url[0]);
//          String json = m.InputstreamToString(is);
//          return json;
        }

        protected void onPostExecute(String json) {
             TextView fragenNr = (TextView)
            findViewById(R.id.FragenText);
             fragenNr.setText(json);


            JSONObject jObj = null;
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            try {

                frage = jObj.getJSONArray(TAG_FRAGE);



                for (int i = 0; i < frage.length(); i++) {
                    JSONObject f = frage.getJSONObject(i);

                    // Storing each json item in variable
                    String text = f.getString(TAG_TEXT);
                    String erklaerung = f.getString(TAG_ERKLAERUNG);

                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put(TAG_TEXT, text);
                    map.put(TAG_ERKLAERUNG, erklaerung);

                    ArrayList<String> antwortenArray = new ArrayList<String>();

                    JSONArray antworten = f.getJSONArray(TAG_ANTWORTEN);
                    for (int j = 0; j < antworten.length(); j++) {
                        JSONObject a = antworten.getJSONObject(j);
                        String tag = TAG_ANTWORTEN_a + (j + 1);
                        antwortenArray.add(a.getString(tag));
                        map.put(tag, antwortenArray.get(j));

                    }

                    map.put("anzahlAntworten", antworten.length());

                    ArrayList<String> richtigeantwortenArray = new ArrayList<String>();
                    JSONArray richtigeantworten = f
                            .getJSONArray(TAG_RICHTIGEANTWORTEN);
                    for (int k = 0; k < richtigeantworten.length(); k++) {
                        JSONObject ra = richtigeantworten.getJSONObject(k);
                        String tag = TAG_RICHTIGEANTWORTEN_ra + (k + 1);
                        richtigeantwortenArray.add(ra.getString(tag));
                        map.put(tag, richtigeantwortenArray.get(k));

                    }
                    map.put("anzahlRichtigerAntworten",richtigeantworten.length());
                    fragenUndAntworten.add(map);
                    fragenListe.add(text);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            View weiterButton = findViewById(R.id.weiterButton);
            weiterButton.setOnClickListener(Fragen.this);
            weiterButton.performClick();

        }

    }

2 个答案:

答案 0 :(得分:2)

不要试图自己生成JSON。生成数据结构,并使用JSON解析器/生成器将此数据结构实际转换为JSON字符串。生成器将负责为您转义字符。有许多免费提供的JSON API。有关列表,请参阅http://json.org/

答案 1 :(得分:-2)

使用json.jar创建json对象或数组...它有创建和处理json的方法......