猿问

无法使 json 对 recyclerview 有效

我正在尝试使用 Gson 和 recyclerview 进行 JSON 处理。我的 JSON 不完全有效。在我的 JSON 中,food 字段只有一个字符串被引用,而另一个则不被引用。请参阅下面我的 JSON...


[


    {"quantity" = 2, 

    "price" = 15, 

    "food" = "Fried" Rice}, 


    {"quantity" = 2,

    "price" = 20,

    "food" = "Rice" and Stew}


    ]

您可以看到 Fried 有引号,而 Rice 没有引号,同样,Rice 和 Stew 也有同样的情况。最初是这样的……


[


    {quantity = 2, 

    price = 15, 

    food = Fried Rice}, 


    {quantity = 2,

    price = 20,

    food = Rice and Stew}


    ]

我的活动类代码...


Bundle extras = getIntent().getExtras();


    if (extras != null) {

        String listOfFood = extras.getString("foods");

        listOfFood = listOfFood.replaceAll("([\\w]+)[ ]*=", "\"$1\" ="); // to quote before = value

        listOfFood = listOfFood.replaceAll("=[ ]*([\\w@\\.]+)", "= \"$1\""); // to quote after = value, add special character as needed to the exclusion list in regex

        listOfFood = listOfFood.replaceAll("=[ ]*\"([\\d]+)\"", "= $1"); // to un-quote decimal value

        listOfFood = listOfFood.replaceAll("\"true\"", "true"); // to un-quote boolean

        listOfFood = listOfFood.replaceAll("\"false\"", "false"); // to un-quote boolean


        Log.d(TAG, "onCreate: "+listOfFood);


        GsonBuilder builder = new GsonBuilder();

        Gson mGson = builder.create();

        List<FoodOrder> posts = new ArrayList<FoodOrder>();

        posts = Arrays.asList(mGson.fromJson(listOfFood, FoodOrder[].class));

        adapter = new RecyclerViewAdapter(FoodsOrderedActivity.this, posts);

        recyclerView.setAdapter(adapter);

    }

我需要将炒饭放在引号之间的食品字段,作为米饭和炖菜的引号,或者是否有解决方法,我想知道。


忽然笑
浏览 122回答 3
3回答

九州编程

根据您的代码。(尝试转换listOfFood为 JSON )我修改了 2 行代码,如下所示&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;listOfFood&nbsp;=&nbsp;listOfFood.replaceAll("(\\s*)([^{,\\s]+)(\\s*)=","$1\"$2\"$3:");&nbsp;//&nbsp;to&nbsp;quote&nbsp;before&nbsp;=&nbsp;value&nbsp;and&nbsp;replace&nbsp;=&nbsp;by&nbsp;: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;listOfFood&nbsp;=&nbsp;listOfFood.replaceAll("(:\\s*)([^\\s,{}](\\s*[^\\s,{}]+)*)",&nbsp;"$1\"$2\"");&nbsp;//&nbsp;to&nbsp;quote&nbsp;after&nbsp;=&nbsp;value&nbsp;(=&nbsp;now&nbsp;became&nbsp;:)

白衣染霜花

json 结构应该是这样的:[{"数量" : 2, "价格" : 15, "食物" : "炒饭"}, {"数量" : 2, "价格" : 20, "食物" : "米饭和炖菜"}]

catspeake

json 结构应如下所示 [ { "Key1" : "value1", "Key2" : "value2", }, { "Key1" : "value1", "Key2" : "value2", }
随时随地看视频慕课网APP

相关分类

Java
我要回答