如何创建json的字符串表示形式

时间:2012-02-27 10:35:16

标签: android json

嘿有男人和女孩我有这个代码,将json保存为字符串表示,我仍然有点理解实体部分如何工作,并需要知道如何更改我的代码,以便它的工作原理,这是我得错误,

Error saving string java.lang.NumberFormatException: unable to parse '[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]' as integer

我昨晚得到了某人的帮助,几乎让我在那里,但仍然需要更多地了解它是如何工作的,并且我在这里得到解析错误是我的完整代码

    public class MainActivity extends Activity {
String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    //button that saves the file from mySQL
    Button save = (Button) findViewById(R.id.downloadBtn);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            saveJson();             
        }
    });

    //Button that opens the file from InternalMemory
    Button open = (Button) findViewById(R.id.showBtn);
    open.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            openJson();             
        }
    });


//end of onCreate() 
}


//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
    TextView test = (TextView) findViewById(R.id.showView);


    try{
        //connects to mySQL
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
        HttpResponse response = client.execute(post);
        //captures the response
        entity = response.getEntity();
        InputStream entityStream = entity.getContent();
        StringBuilder entityStringBuilder = new StringBuilder();
        byte [] buffer = new byte[1024];
        int bytesReadCount;
        while ((bytesReadCount = entityStream.read(buffer)) > 0)  {
            entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
        }
        entityString = entityStringBuilder.toString();
        responseInteger = Integer.valueOf(entityString);
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }
    try{
        //is = entity.getContent();
        String FILENAME = "story.json";
        //gives file name
        FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
        //creates new StreamWriter
        OutputStreamWriter writer = new OutputStreamWriter(output);
        //writes json with file name story.json
        writer.write(entityString);
        writer.flush();
        //closes writer
        writer.close();

    }catch(Exception e) {
         Log.e("log_tag", "Error saving string "+e.toString());
    }

//end of saveJson()
}

public void openJson(){
    TextView test = (TextView) findViewById(R.id.showView);



    try{
        FileInputStream fileInput = openFileInput("story.json");

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
        StringBuilder strBuilder = new StringBuilder();
            String line = null;
            while ((line = inputReader.readLine()) != null) {
                strBuilder.append(line + "\n");
            }
            fileInput.close();
            storyObj = strBuilder.toString();

    }catch(IOException e){
         Log.e("log_tag", "Error building string "+e.toString());
    }

    try{
        JSONArray jArray = new JSONArray(storyObj);
        String storyNames = "";
        for(int i = 0;i<jArray.length();i++){
            storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
        }
        test.setText(storyNames);

    }catch(JSONException e) {
         Log.e("log_tag", "Error returning string "+e.toString());
    }
    return;
//and of openJson() 
}




//end of class body    
}

3 个答案:

答案 0 :(得分:3)

我猜你的代码在这方面失败了:

responseInteger = Integer.valueOf(entityString);

经过一番检查后,我发现你的JSON是:

[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]

使用JSON Viewer仔细检查,我发现你的结构是这样的:

enter image description here

问题是

我在这个JSON中看不到任何整数。您可能必须使用JSONObjectJSONArray的组合来正确解析它。

答案 1 :(得分:2)

你的问题就在这一行

    responseInteger = Integer.valueOf(entityString);

entityString是

'[{"story_name":"Story One"},{"story_name":"Story Two"},{"story_name":"Story Three"},{"story_name":"Story Four"},{"story_name":"Story Five"},{"story_name":"Story Six"}]'

当Integer.valueOf尝试解析它时,它无法将其解析为整数,因此它会抛出NumberFormatException。

答案 2 :(得分:2)

示例JSon字符串:

{
      Stories: 
      [
          {
            "story_name": "Story One"
          },
          {
            "story_name": "Story Two"
          }

      ]
}

创建一个类:

public class Story
{
  public String stort_name;
}

class CollectionOfStories 
{
    public List<Story> Stories;
    public CollectionOfSections()
    {
        Stories= new ArrayList<Story>(); 
    }
}

最后:

private CollectionOfStories convertDataFromJSonToObject(String jsonString)
{
    JSONObject jso;     
    CollectionOfStories colStories = new CollectionOfStories();

    try 
    {
        jso = new JSONObject(jsonString);
        JSONArray ja = jso.getJSONArray("Stories");

        for (int i = 0; i < ja.length(); i++) 
        {
            Story s = new Story();
            JSONObject jsonSection = ja.getJSONObject(i);

            s.stort_name = jsonSection.getString("story_name");

           //add it to sections list
           colStories.Stories.add(s);
        }
    } 
    catch (NumberFormatException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (JSONException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return colStories;

}