我正在尝试使用Gson和recyclerview进行JSON。我的 JSON 不完全有效。在我的 JSON 中,食物字段只有一个字符串被引用,另一个没有引用。请在下面查看我的 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);
}
我需要将炒饭放在引号之间的食物领域,作为米饭和炖菜的引号,或者如果有解决方法,我想知道。
谢谢
基于你的代码。(尝试将listOfFood
转换为JSON( 我修改了你的 2 行代码作为波纹管
listOfFood = listOfFood.replaceAll("(\s*)([^{,\s]+)(\s*)=","$1"$2"$3:"); // to quote before = value and replace = by :
listOfFood = listOfFood.replaceAll("(:\s*)([^\s,{}](\s*[^\s,{}]+)*)", "$1"$2""); // to quote after = value (= now became :)
json 结构应如下所示 [ { "键 1" : "值 1", "键 2" : "值 2", }, { "键 1" : "值 1", "键 2" : "值 2", }
]
json 结构应该是这样的:
[{"数量" : 2, "价格" : 15, "食物" : "炒饭"}, {"数量" : 2, "价格" : 20, "食物" : "米饭和炖菜"}]