如何创建一个字符串重新JSON的$​​ P $ psentation [英] how to create a string representation of json

查看:148
本文介绍了如何创建一个字符串重新JSON的$​​ P $ psentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿家伙和女孩我有这个code,节省了JSON作为字符串重新presentation,我还是巡航能力有点麻烦理解实体部分是如何工作的,并需要了解如何改变我的code,这样它的工作原理,这是错误即时得到,

 错误节省字符串java.lang.NumberFormatException:无法解析[{story_name:故事一},{story_name:故事二},{ story_name:故事三},{story_name:故事四},{story_name:故事五},{story_name:故事六}]'作为整数

我渐渐从别人的帮助,昨晚,几乎让我有,但仍需要它是如何工作和西隧我在这里得到了解析错误是我的全code多了几分理解。

 公共类MainActivity延伸活动{
字符串entityString = NULL;
串storyObj =;
JSON对象= NULL;
HttpEntity实体= NULL;
InputStream为= NULL;
整数responseInteger = NULL;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    //按钮保存从MySQL文件
    按钮保存=(按钮)findViewById(R.id.downloadBtn);
    save.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            saveJson();
        }
    });    //打开从InternalMemory文件按钮
    按钮打开=(按钮)findViewById(R.id.showBtn);
    open.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            openJson();
        }
    });
//的onCreate结束()
}
// saveJson拉从MySQL服务器的JSON文件,然后保存该文件在其JSON类型如以.json
公共无效saveJson(){
    TextView的测试=(的TextView)findViewById(R.id.showView);
    尝试{
        //连接到MySQL
        HttpClient的客户端=新DefaultHttpClient();
        HttpPost后=新HttpPost(http://10.0.2.2/textures_story_list.php);
        HTT presponse响应= client.execute(岗位);
        //捕获响应
        实体= response.getEntity();
        InputStream的entityStream = entity.getContent();
        StringBuilder的entityStringBuilder =新的StringBuilder();
        字节[]缓冲区=新的字节[1024];
        INT bytesReadCount;
        而((bytesReadCount = entityStream.read(缓冲液))大于0){
            entityStringBuilder.append(新的String(缓冲,0,bytesReadCount));
        }
        entityString = entityStringBuilder.toString();
        responseInteger = Integer.valueOf(entityString);
    }赶上(例外五){
         Log.e(log_tag,在HTTP连接错误+ e.toString());
    }
    尝试{
        //是= entity.getContent();
        字符串文件名=story.json;
        //给文件名
        FileOutputStream中输出= openFileOutput(文件名,MODE_WORLD_READABLE);
        //创建新的StreamWriter
        OutputStreamWriter作家=新OutputStreamWriter(输出);
        //使用文件名story.json写入JSON
        writer.write(entityString);
        writer.flush();
        //关闭作家
        writer.close();    }赶上(例外五){
         Log.e(log_tag,错误保存字符串+ e.toString());
    }// saveJson结束()
}公共无效openJson(){
    TextView的测试=(的TextView)findViewById(R.id.showView);    尝试{
        的FileInputStream的FileInput = openFileInput(story.json);        的BufferedReader inputReader =新的BufferedReader(新的InputStreamReader(的FileInput,UTF-8),8);
        StringBuilder的strBuilder =新的StringBuilder();
            串线= NULL;
            而((行= inputReader.readLine())!= NULL){
                strBuilder.append(行+\\ n);
            }
            fileInput.close();
            storyObj = strBuilder.toString();    }赶上(IOException异常五){
         Log.e(log_tag,错误建筑物字符串+ e.toString());
    }    尝试{
        JSONArray jArray =新JSONArray(storyObj);
        串storyNames =;
        的for(int i = 0; I< jArray.length();我++){
            storyNames + = jArray.getJSONObject(ⅰ).getString(story_name)+\\ N的;
        }
        test.setText(storyNames);    }赶上(JSONException E){
         Log.e(log_tag,错误返回字符串+ e.toString());
    }
    返回;
//和openJson的()
}
//类体结束
}


解决方案

我的猜测是你的code未能在这行:

  responseInteger = Integer.valueOf(entityString);

一点点检查后,我看到你JSON是:

  [{story_name:故事一},{story_name:故事二},{story_name:故事三},{story_name :故事四},{story_name:故事五},{story_name:故事六}]

使用A仔细检查 JSON查看器,我看你的结构是这样的:

的问题是

我看不出在这个JSON的任意整数。您可能需要使用的JSONObject 并的 JSONArray 解析你的正确。

hey there guys and girls i have this code that saves json as a string representation, i still haveing a little trouble understanding how the entity section works, and need to know how to change my code so that it works, this is the error im getting,

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

i was getting help from someone last night that almost got me there but still need a little more understanding of how it works and wht i get the parse error here is my full code

    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    
}

解决方案

My guess it your code failed at this lines:

responseInteger = Integer.valueOf(entityString);

After a little inspection, I see that your JSON is:

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

A closer inspection using JSON Viewer, I see that your structure is like this:

The problem is

I don't see any integer in this JSON. You might have to use a combination of JSONObject and JSONArray to parse your it properly.

这篇关于如何创建一个字符串重新JSON的$​​ P $ psentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆