如何修改反序列化的对象

时间:2016-04-27 09:10:30

标签: c# json

我有一个JSON字符串,如下所示

SELECT CASE WHEN EXISTS (SELECT 1
                         FROM mytable m1
                         JOIN mytable m2
                           ON m2.type_count = m1.type_count + 1
                         JOIN mytable m3
                           ON m3.type_count = m1.type_count + 2
                         JOIN mytable m4
                           ON m4.type_count = m1.type_count + 3
                         WHERE m1.post_type = 'attachment' 
                           AND m2.post_type = 'attachment' 
                           AND m3.post_type = 'attachment'
                           AND m4.post_type = 'attachment') 
             THEN 1 
             ELSE 0 END AS result

我想将其转换为以下格式

string str = "{"Id":["1799"],"Type":1,"Date":null,"Group":null,"Ids":1799}";

简而言之,我想删除" Ids"并转换" Id"值为字符串。

为此,我尝试反序列化此字符串,如下所示 -

{"Id":1799,"Type":1,"Date":null,"Group":null }

但在这里我被困住了。如何从此对象中删除/更改值。 我尝试将此对象转换为数组和列表,但无法在其中找到删除/修改选项。

2 个答案:

答案 0 :(得分:2)

也许你可以使用http://www.newtonsoft.com/json的.NET的JSON框架(也可以作为nuget包使用)

然后您可以使用以下内容反序列化到您的对象

while (count<jsonArray.length()) {

    JSONObject SA=jsonArray.getJSONObject(count);
    name=SA.getString("name");
    description=SA.getString("description");
    price=SA.getString("price");

    Promotions promotions=new Promotions(name,description,price);
    promoAdapter.add(promotions);
    count++;

}

然后可能为您的输出创建一个不同的对象,并有一个构造函数接受原始对象作为输入,然后将其序列化为Json。然后,构造函数必须执行您需要的任何内部转换/更改。

string str = "{"Id":["1799"],"Type":1,"Date":null,"Group":null,"Ids":1799}";
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);

答案 1 :(得分:1)

Expando Object。

str newJson = JsonConvert.SerializeObject(newStr);

最初,使用NewtonJson lib

反序列化json
{"Id":1799,"Type":1,"Date":null,"Group":null

然后serilize newStr:

 // decode image
        public Bitmap decodeFile(String filePath) {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFile(filePath, o2);            
            return bitmap;
        }

输出: {{1}}}