简体   繁体   English

如何使用Java Jackson更新JSON文件中的值

[英]How update the value in json file using java jackson

My Json file will be something like below. 我的Json文件将如下所示。 (List(List)) (名单(名单))

[[0,1759,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,1759]
[1,1533,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,1533]
[2,2638,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,2638]
[3,2639,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,2639]
[4,2640,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,2640]]

I want to replace the value in 3rd list (5th index in 3rd list). 我想替换第3个列表中的值(第3个列表中的第5个索引)。 ie: [2,2638,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,2638] 即: [2,2638,10.0,20.0,30.0,40.0,50.0,60.0,70.0,590,2638]

and i want to change the value 30.0 as 10.0. 我想将值30.0更改为10.0。 How to do this change without getting whole file data. 如何在不获取整个文件数据的情况下进行更改。

As far my knowledge I'm afraid that you can't do without reading the whole file if you want use JSON. 据我所知,如果您想使用JSON,恐怕您不能不读取整个文件。

Try this can be any help 试试这个可以有什么帮助

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.ListIterator;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author Ravi P
 */
public class Test {

    public static void main( String[] args ) {

        try {

            List<List<Integer>> jsonParentArr = new ObjectMapper().readValue( new File( "C:\\tmp\\Details.json" ), new TypeReference<List<List<Integer>>>() {
            } ); // read the data from file and form a list

            System.out.println( jsonParentArr.get( 2 ) ); // array values before replacing 30

            ListIterator<Integer> childJsonArr = jsonParentArr.get( 2 ).listIterator(); // get the 3rd array

            while ( childJsonArr.hasNext() ) {

                if ( childJsonArr.next() == 30 ) { // replace if the value to 10.0 if the exsting value is 30

                    childJsonArr.set( 10 );
                }
            }

            System.out.println( jsonParentArr.get( 2 ) ); // array values after replacing 30

            try (BufferedWriter bWriter = new BufferedWriter( new FileWriter( "C:\\tmp\\Details.json" ) )) {

                bWriter.write( jsonParentArr.toString() ); // write back the result to same file

            } catch ( Exception e ) {

                e.printStackTrace();
            }

        } catch ( Exception e ) {

            e.printStackTrace();

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM